repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_minion_update
python
def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions()
Associate grains data with a minion and publish minion update
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L60-L76
[ "def publish_minions(self):\n '''\n Publishes minions as a list of dicts.\n '''\n log.debug('in publish minions')\n minions = {}\n\n log.debug('starting loop')\n for minion, minion_info in six.iteritems(self.minions):\n log.debug(minion)\n # log.debug(minion_info)\n curr_minion = {}\n curr_minion.update(minion_info)\n curr_minion.update({'id': minion})\n minions[minion] = curr_minion\n log.debug('ended loop')\n ret = {'minions': minions}\n self.handler.write_message(\n salt.utils.json.dumps(ret) + str('\\n\\n')) # future lint: disable=blacklisted-function\n" ]
class SaltInfo(object): ''' Class to handle processing and publishing of "real time" Salt upates. ''' def __init__(self, handler): ''' handler is expected to be the server side end of a websocket connection. ''' self.handler = handler # These represent a "real time" view into Salt's jobs. self.jobs = {} # This represents a "real time" view of minions connected to # Salt. self.minions = {} def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n')) # future lint: disable=blacklisted-function def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub) def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs) def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs) def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions() def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions() def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_ret_job_event
python
def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs)
Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L78-L100
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def publish(self, key, data):\n '''\n Publishes the data to the event stream.\n '''\n publish_data = {key: data}\n pub = salt.utils.json.dumps(publish_data) + str('\\n\\n') # future lint: disable=blacklisted-function\n self.handler.write_message(pub)\n" ]
class SaltInfo(object): ''' Class to handle processing and publishing of "real time" Salt upates. ''' def __init__(self, handler): ''' handler is expected to be the server side end of a websocket connection. ''' self.handler = handler # These represent a "real time" view into Salt's jobs. self.jobs = {} # This represents a "real time" view of minions connected to # Salt. self.minions = {} def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n')) # future lint: disable=blacklisted-function def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub) def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions() def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs) def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions() def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions() def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_new_job_event
python
def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs)
Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L102-L129
[ "def publish(self, key, data):\n '''\n Publishes the data to the event stream.\n '''\n publish_data = {key: data}\n pub = salt.utils.json.dumps(publish_data) + str('\\n\\n') # future lint: disable=blacklisted-function\n self.handler.write_message(pub)\n" ]
class SaltInfo(object): ''' Class to handle processing and publishing of "real time" Salt upates. ''' def __init__(self, handler): ''' handler is expected to be the server side end of a websocket connection. ''' self.handler = handler # These represent a "real time" view into Salt's jobs. self.jobs = {} # This represents a "real time" view of minions connected to # Salt. self.minions = {} def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n')) # future lint: disable=blacklisted-function def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub) def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions() def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs) def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions() def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions() def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_key_event
python
def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions()
Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L131-L149
[ "def publish_minions(self):\n '''\n Publishes minions as a list of dicts.\n '''\n log.debug('in publish minions')\n minions = {}\n\n log.debug('starting loop')\n for minion, minion_info in six.iteritems(self.minions):\n log.debug(minion)\n # log.debug(minion_info)\n curr_minion = {}\n curr_minion.update(minion_info)\n curr_minion.update({'id': minion})\n minions[minion] = curr_minion\n log.debug('ended loop')\n ret = {'minions': minions}\n self.handler.write_message(\n salt.utils.json.dumps(ret) + str('\\n\\n')) # future lint: disable=blacklisted-function\n" ]
class SaltInfo(object): ''' Class to handle processing and publishing of "real time" Salt upates. ''' def __init__(self, handler): ''' handler is expected to be the server side end of a websocket connection. ''' self.handler = handler # These represent a "real time" view into Salt's jobs. self.jobs = {} # This represents a "real time" view of minions connected to # Salt. self.minions = {} def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n')) # future lint: disable=blacklisted-function def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub) def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions() def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs) def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs) def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions() def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process_presence_events
python
def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions()
Check if any minions have connected or dropped. Send a message to the client if they have.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L151-L202
[ "def run(self, low):\n '''\n Execute the specified function in the specified client by passing the\n lowstate\n '''\n # Eauth currently requires a running daemon and commands run through\n # this method require eauth so perform a quick check to raise a\n # more meaningful error.\n if not self._is_master_running():\n raise salt.exceptions.SaltDaemonNotRunning(\n 'Salt Master is not available.')\n\n if low.get('client') not in CLIENTS:\n raise salt.exceptions.SaltInvocationError(\n 'Invalid client specified: \\'{0}\\''.format(low.get('client')))\n\n if not ('token' in low or 'eauth' in low) and low['client'] != 'ssh':\n raise salt.exceptions.EauthAuthenticationError(\n 'No authentication credentials given')\n\n l_fun = getattr(self, low['client'])\n f_call = salt.utils.args.format_call(l_fun, low)\n return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))\n", "def publish_minions(self):\n '''\n Publishes minions as a list of dicts.\n '''\n log.debug('in publish minions')\n minions = {}\n\n log.debug('starting loop')\n for minion, minion_info in six.iteritems(self.minions):\n log.debug(minion)\n # log.debug(minion_info)\n curr_minion = {}\n curr_minion.update(minion_info)\n curr_minion.update({'id': minion})\n minions[minion] = curr_minion\n log.debug('ended loop')\n ret = {'minions': minions}\n self.handler.write_message(\n salt.utils.json.dumps(ret) + str('\\n\\n')) # future lint: disable=blacklisted-function\n" ]
class SaltInfo(object): ''' Class to handle processing and publishing of "real time" Salt upates. ''' def __init__(self, handler): ''' handler is expected to be the server side end of a websocket connection. ''' self.handler = handler # These represent a "real time" view into Salt's jobs. self.jobs = {} # This represents a "real time" view of minions connected to # Salt. self.minions = {} def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n')) # future lint: disable=blacklisted-function def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub) def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions() def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs) def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs) def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions() def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
saltstack/salt
salt/netapi/rest_tornado/event_processor.py
SaltInfo.process
python
def process(self, salt_data, token, opts): ''' Process events and publish data ''' log.debug('In process %s', threading.current_thread()) log.debug(salt_data['tag']) log.debug(salt_data) parts = salt_data['tag'].split('/') if len(parts) < 2: return # TBD: Simplify these conditional expressions if parts[1] == 'job': log.debug('In job part 1') if parts[3] == 'new': log.debug('In new job') self.process_new_job_event(salt_data) # if salt_data['data']['fun'] == 'grains.items': # self.minions = {} elif parts[3] == 'ret': log.debug('In ret') self.process_ret_job_event(salt_data) if salt_data['data']['fun'] == 'grains.items': self.process_minion_update(salt_data) elif parts[1] == 'key': log.debug('In key') self.process_key_event(salt_data) elif parts[1] == 'presence': self.process_presence_events(salt_data, token, opts)
Process events and publish data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/event_processor.py#L204-L233
[ "def process_minion_update(self, event_data):\n '''\n Associate grains data with a minion and publish minion update\n '''\n tag = event_data['tag']\n event_info = event_data['data']\n\n mid = tag.split('/')[-1]\n\n if not self.minions.get(mid, None):\n self.minions[mid] = {}\n\n minion = self.minions[mid]\n\n minion.update({'grains': event_info['return']})\n log.debug(\"In process minion grains update with minions=%s\", self.minions)\n self.publish_minions()\n", "def process_ret_job_event(self, event_data):\n '''\n Process a /ret event returned by Salt for a particular minion.\n These events contain the returned results from a particular execution.\n '''\n tag = event_data['tag']\n event_info = event_data['data']\n\n _, _, jid, _, mid = tag.split('/')\n job = self.jobs.setdefault(jid, {})\n\n minion = job.setdefault('minions', {}).setdefault(mid, {})\n minion.update({'return': event_info['return']})\n minion.update({'retcode': event_info['retcode']})\n minion.update({'success': event_info['success']})\n\n job_complete = all([minion['success'] for mid, minion\n in six.iteritems(job['minions'])])\n\n if job_complete:\n job['state'] = 'complete'\n\n self.publish('jobs', self.jobs)\n", "def process_new_job_event(self, event_data):\n '''\n Creates a new job with properties from the event data\n like jid, function, args, timestamp.\n\n Also sets the initial state to started.\n\n Minions that are participating in this job are also noted.\n\n '''\n job = None\n tag = event_data['tag']\n event_info = event_data['data']\n minions = {}\n for mid in event_info['minions']:\n minions[mid] = {'success': False}\n\n job = {\n 'jid': event_info['jid'],\n 'start_time': event_info['_stamp'],\n 'minions': minions, # is a dictionary keyed by mids\n 'fun': event_info['fun'],\n 'tgt': event_info['tgt'],\n 'tgt_type': event_info['tgt_type'],\n 'state': 'running',\n }\n self.jobs[event_info['jid']] = job\n self.publish('jobs', self.jobs)\n", "def process_key_event(self, event_data):\n '''\n Tag: salt/key\n Data:\n {'_stamp': '2014-05-20T22:45:04.345583',\n 'act': 'delete',\n 'id': 'compute.home',\n 'result': True}\n '''\n\n tag = event_data['tag']\n event_info = event_data['data']\n\n if event_info['act'] == 'delete':\n self.minions.pop(event_info['id'], None)\n elif event_info['act'] == 'accept':\n self.minions.setdefault(event_info['id'], {})\n\n self.publish_minions()\n", "def process_presence_events(self, salt_data, token, opts):\n '''\n Check if any minions have connected or dropped.\n Send a message to the client if they have.\n '''\n log.debug('In presence')\n changed = False\n\n # check if any connections were dropped\n if set(salt_data['data'].get('lost', [])):\n dropped_minions = set(salt_data['data'].get('lost', []))\n else:\n dropped_minions = set(self.minions) - set(salt_data['data'].get('present', []))\n\n for minion in dropped_minions:\n changed = True\n log.debug('Popping %s', minion)\n self.minions.pop(minion, None)\n\n # check if any new connections were made\n if set(salt_data['data'].get('new', [])):\n log.debug('got new minions')\n new_minions = set(salt_data['data'].get('new', []))\n changed = True\n elif set(salt_data['data'].get('present', [])) - set(self.minions):\n log.debug('detected new minions')\n new_minions = set(salt_data['data'].get('present', [])) - set(self.minions)\n changed = True\n else:\n new_minions = []\n\n tgt = ','.join(new_minions)\n for mid in new_minions:\n log.debug('Adding minion')\n self.minions[mid] = {}\n\n if tgt:\n changed = True\n client = salt.netapi.NetapiClient(opts)\n client.run(\n {\n 'fun': 'grains.items',\n 'tgt': tgt,\n 'expr_type': 'list',\n 'mode': 'client',\n 'client': 'local',\n 'asynchronous': 'local_async',\n 'token': token,\n })\n\n if changed:\n self.publish_minions()\n" ]
class SaltInfo(object): ''' Class to handle processing and publishing of "real time" Salt upates. ''' def __init__(self, handler): ''' handler is expected to be the server side end of a websocket connection. ''' self.handler = handler # These represent a "real time" view into Salt's jobs. self.jobs = {} # This represents a "real time" view of minions connected to # Salt. self.minions = {} def publish_minions(self): ''' Publishes minions as a list of dicts. ''' log.debug('in publish minions') minions = {} log.debug('starting loop') for minion, minion_info in six.iteritems(self.minions): log.debug(minion) # log.debug(minion_info) curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions[minion] = curr_minion log.debug('ended loop') ret = {'minions': minions} self.handler.write_message( salt.utils.json.dumps(ret) + str('\n\n')) # future lint: disable=blacklisted-function def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub) def process_minion_update(self, event_data): ''' Associate grains data with a minion and publish minion update ''' tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) log.debug("In process minion grains update with minions=%s", self.minions) self.publish_minions() def process_ret_job_event(self, event_data): ''' Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution. ''' tag = event_data['tag'] event_info = event_data['data'] _, _, jid, _, mid = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) minion.update({'success': event_info['success']}) job_complete = all([minion['success'] for mid, minion in six.iteritems(job['minions'])]) if job_complete: job['state'] = 'complete' self.publish('jobs', self.jobs) def process_new_job_event(self, event_data): ''' Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted. ''' job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = { 'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, # is a dictionary keyed by mids 'fun': event_info['fun'], 'tgt': event_info['tgt'], 'tgt_type': event_info['tgt_type'], 'state': 'running', } self.jobs[event_info['jid']] = job self.publish('jobs', self.jobs) def process_key_event(self, event_data): ''' Tag: salt/key Data: {'_stamp': '2014-05-20T22:45:04.345583', 'act': 'delete', 'id': 'compute.home', 'result': True} ''' tag = event_data['tag'] event_info = event_data['data'] if event_info['act'] == 'delete': self.minions.pop(event_info['id'], None) elif event_info['act'] == 'accept': self.minions.setdefault(event_info['id'], {}) self.publish_minions() def process_presence_events(self, salt_data, token, opts): ''' Check if any minions have connected or dropped. Send a message to the client if they have. ''' log.debug('In presence') changed = False # check if any connections were dropped if set(salt_data['data'].get('lost', [])): dropped_minions = set(salt_data['data'].get('lost', [])) else: dropped_minions = set(self.minions) - set(salt_data['data'].get('present', [])) for minion in dropped_minions: changed = True log.debug('Popping %s', minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data['data'].get('new', [])): log.debug('got new minions') new_minions = set(salt_data['data'].get('new', [])) changed = True elif set(salt_data['data'].get('present', [])) - set(self.minions): log.debug('detected new minions') new_minions = set(salt_data['data'].get('present', [])) - set(self.minions) changed = True else: new_minions = [] tgt = ','.join(new_minions) for mid in new_minions: log.debug('Adding minion') self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { 'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'asynchronous': 'local_async', 'token': token, }) if changed: self.publish_minions()
saltstack/salt
salt/client/ssh/wrapper/mine.py
get
python
def get(tgt, fun, tgt_type='glob', roster='flat'): ''' Get data from the mine based on the target, function and tgt_type This will actually run the function on all targeted minions (like publish.publish), as salt-ssh clients can't update the mine themselves. We will look for mine_functions in the roster, pillar, and master config, in that order, looking for a match for the defined function Targets can be matched based on any standard matching system that can be matched on the defined roster (in salt-ssh) via these keywords:: CLI Example: .. code-block:: bash salt-ssh '*' mine.get '*' network.interfaces salt-ssh '*' mine.get 'myminion' network.interfaces roster=flat salt-ssh '*' mine.get '192.168.5.0' network.ipaddrs roster=scan ''' # Set up opts for the SSH object opts = copy.deepcopy(__context__['master_opts']) minopts = copy.deepcopy(__opts__) opts.update(minopts) if roster: opts['roster'] = roster opts['argv'] = [fun] opts['selected_target_option'] = tgt_type opts['tgt'] = tgt opts['arg'] = [] # Create the SSH object to handle the actual call ssh = salt.client.ssh.SSH(opts) # Run salt-ssh to get the minion returns rets = {} for ret in ssh.run_iter(mine=True): rets.update(ret) cret = {} for host in rets: if 'return' in rets[host]: cret[host] = rets[host]['return'] else: cret[host] = rets[host] return cret
Get data from the mine based on the target, function and tgt_type This will actually run the function on all targeted minions (like publish.publish), as salt-ssh clients can't update the mine themselves. We will look for mine_functions in the roster, pillar, and master config, in that order, looking for a match for the defined function Targets can be matched based on any standard matching system that can be matched on the defined roster (in salt-ssh) via these keywords:: CLI Example: .. code-block:: bash salt-ssh '*' mine.get '*' network.interfaces salt-ssh '*' mine.get 'myminion' network.interfaces roster=flat salt-ssh '*' mine.get '192.168.5.0' network.ipaddrs roster=scan
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/mine.py#L17-L63
[ "def run_iter(self, mine=False, jid=None):\n '''\n Execute and yield returns as they come in, do not print to the display\n\n mine\n The Single objects will use mine_functions defined in the roster,\n pillar, or master config (they will be checked in that order) and\n will modify the argv with the arguments from mine_functions\n '''\n fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])\n jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))\n\n # Save the invocation information\n argv = self.opts['argv']\n\n if self.opts.get('raw_shell', False):\n fun = 'ssh._raw'\n args = argv\n else:\n fun = argv[0] if argv else ''\n args = argv[1:]\n\n job_load = {\n 'jid': jid,\n 'tgt_type': self.tgt_type,\n 'tgt': self.opts['tgt'],\n 'user': self.opts['user'],\n 'fun': fun,\n 'arg': args,\n }\n\n # save load to the master job cache\n if self.opts['master_job_cache'] == 'local_cache':\n self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())\n else:\n self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)\n\n for ret in self.handle_ssh(mine=mine):\n host = next(six.iterkeys(ret))\n self.cache_job(jid, host, ret[host], fun)\n if self.event:\n id_, data = next(six.iteritems(ret))\n if isinstance(data, six.text_type):\n data = {'return': data}\n if 'id' not in data:\n data['id'] = id_\n data['jid'] = jid # make the jid in the payload the same as the jid in the tag\n self.event.fire_event(\n data,\n salt.utils.event.tagify(\n [jid, 'ret', host],\n 'job'))\n yield ret\n" ]
# -*- coding: utf-8 -*- ''' Wrapper function for mine operations for salt-ssh .. versionadded:: 2015.5.0 ''' # Import python libs from __future__ import absolute_import, print_function import copy # Import salt libs import salt.client.ssh
saltstack/salt
salt/utils/timeout.py
wait_for
python
def wait_for(func, timeout=10, step=1, default=None, func_args=(), func_kwargs=None): ''' Call `func` at regular intervals and Waits until the given function returns a truthy value within the given timeout and returns that value. @param func: @type func: function @param timeout: @type timeout: int | float @param step: Interval at which we should check for the value @type step: int | float @param default: Value that should be returned should `func` not return a truthy value @type default: @param func_args: *args for `func` @type func_args: list | tuple @param func_kwargs: **kwargs for `func` @type func_kwargs: dict @return: `default` or result of `func` ''' if func_kwargs is None: func_kwargs = dict() max_time = time.time() + timeout # Time moves forward so we might not reenter the loop if we step too long step = min(step or 1, timeout) * BLUR_FACTOR ret = default while time.time() <= max_time: call_ret = func(*func_args, **func_kwargs) if call_ret: ret = call_ret break else: time.sleep(step) # Don't allow cases of over-stepping the timeout step = min(step, max_time - time.time()) * BLUR_FACTOR if time.time() > max_time: log.warning("Exceeded waiting time (%s seconds) to exectute %s", timeout, func) return ret
Call `func` at regular intervals and Waits until the given function returns a truthy value within the given timeout and returns that value. @param func: @type func: function @param timeout: @type timeout: int | float @param step: Interval at which we should check for the value @type step: int | float @param default: Value that should be returned should `func` not return a truthy value @type default: @param func_args: *args for `func` @type func_args: list | tuple @param func_kwargs: **kwargs for `func` @type func_kwargs: dict @return: `default` or result of `func`
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/timeout.py#L12-L50
[ "def vb_get_network_addresses(machine_name=None, machine=None, wait_for_pattern=None):\n '''\n TODO distinguish between private and public addresses\n\n A valid machine_name or a machine is needed to make this work!\n\n !!!\n Guest prerequisite: GuestAddition\n !!!\n\n Thanks to Shrikant Havale for the StackOverflow answer http://stackoverflow.com/a/29335390\n\n More information on guest properties: https://www.virtualbox.org/manual/ch04.html#guestadd-guestprops\n\n @param machine_name:\n @type machine_name: str\n @param machine:\n @type machine: IMachine\n @return: All the IPv4 addresses we could get\n @rtype: str[]\n '''\n if machine_name:\n machine = vb_get_box().findMachine(machine_name)\n\n ip_addresses = []\n log.debug(\"checking for power on:\")\n if machine.state == _virtualboxManager.constants.MachineState_Running:\n\n log.debug(\"got power on:\")\n\n #wait on an arbitrary named property\n #for instance use a dhcp client script to set a property via VBoxControl guestproperty set dhcp_done 1\n if wait_for_pattern and not machine.getGuestPropertyValue(wait_for_pattern):\n log.debug(\"waiting for pattern:%s:\", wait_for_pattern)\n return None\n\n _total_slots = machine.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/Count')\n\n #upon dhcp the net count drops to 0 and it takes some seconds for it to be set again\n if not _total_slots:\n log.debug(\"waiting for net count:%s:\", wait_for_pattern)\n return None\n\n try:\n total_slots = int(_total_slots)\n for i in range(total_slots):\n try:\n address = machine.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/{0}/V4/IP'.format(i))\n if address:\n ip_addresses.append(address)\n except Exception as e:\n log.debug(e.message)\n except ValueError as e:\n log.debug(e.message)\n return None\n\n log.debug(\"returning ip_addresses:%s:\", ip_addresses)\n return ip_addresses\n", "def _check_session_state(xp_session, expected_state='Unlocked'):\n '''\n @param xp_session:\n @type xp_session: ISession from the Virtualbox API\n @param expected_state: The constant descriptor according to the docs\n @type expected_state: str\n @return:\n @rtype: bool\n '''\n state_value = getattr(_virtualboxManager.constants, 'SessionState_' + expected_state)\n return xp_session.state == state_value\n", "def _start_machine(machine, session):\n '''\n Helper to try and start machines\n\n @param machine:\n @type machine: IMachine\n @param session:\n @type session: ISession\n @return:\n @rtype: IProgress or None\n '''\n try:\n return machine.launchVMProcess(session, '', '')\n except Exception as e:\n log.debug(e.message, exc_info=True)\n return None\n", "def actual(*args):\n if time.time() >= end:\n return args\n else:\n return False\n", "def actual(**kwargs):\n if time.time() >= end:\n return kwargs\n else:\n return False\n" ]
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import logging import time log = logging.getLogger(__name__) # To give us some leeway when making time-calculations BLUR_FACTOR = 0.95
saltstack/salt
salt/modules/debian_service.py
get_enabled
python
def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' prefix = '/etc/rc[S{0}].d/S'.format(_get_runlevel()) ret = set() lines = glob.glob('{0}*'.format(prefix)) for line in lines: ret.add(re.split(prefix + r'\d+', line)[1]) return sorted(ret)
Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L76-L91
[ "def _get_runlevel():\n '''\n returns the current runlevel\n '''\n out = __salt__['cmd.run']('runlevel')\n # unknown can be returned while inside a container environment, since\n # this is due to a lack of init, it should be safe to assume runlevel\n # 2, which is Debian's default. If not, all service related states\n # will throw an out of range exception here which will cause\n # other functions to fail.\n if 'unknown' in out:\n return '2'\n else:\n return out.split()[1]\n" ]
# -*- coding: utf-8 -*- ''' Service support for Debian systems (uses update-rc.d and /sbin/service) .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import glob import fnmatch import re # Import 3rd-party libs # pylint: disable=import-error from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: enable=import-error # Import salt libs import salt.utils.systemd __func_alias__ = { 'reload_': 'reload' } # Define the module's virtual name __virtualname__ = 'service' log = logging.getLogger(__name__) _DEFAULT_VER = '7.0.0' def __virtual__(): ''' Only work on Debian and when systemd isn't running ''' if __grains__['os'] in ('Debian', 'Raspbian', 'Devuan', 'NILinuxRT') and not salt.utils.systemd.booted(__context__): return __virtualname__ else: return (False, 'The debian_service module could not be loaded: ' 'unsupported OS family and/or systemd running.') def _service_cmd(*args): osmajor = _osrel()[0] if osmajor < '6': cmd = '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) else: cmd = 'service {0} {1}'.format(args[0], ' '.join(args[1:])) return cmd def _get_runlevel(): ''' returns the current runlevel ''' out = __salt__['cmd.run']('runlevel') # unknown can be returned while inside a container environment, since # this is due to a lack of init, it should be safe to assume runlevel # 2, which is Debian's default. If not, all service related states # will throw an out of range exception here which will cause # other functions to fail. if 'unknown' in out: return '2' else: return out.split()[1] def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return sorted(set(get_all()) - set(get_enabled())) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' return name in get_all() def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return name not in get_all() def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = set() lines = glob.glob('/etc/init.d/*') for line in lines: service = line.split('/etc/init.d/')[1] # Remove README. If it's an enabled service, it will be added back in. if service != 'README': ret.add(service) return sorted(ret | set(get_enabled())) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not __salt__['cmd.retcode'](cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not __salt__['cmd.retcode'](cmd) def force_reload(name): ''' Force-reload the named service CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' cmd = _service_cmd(name, 'force-reload') return not __salt__['cmd.retcode'](cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not __salt__['cmd.retcode'](cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def _osrel(): osrel = __grains__.get('osrelease', _DEFAULT_VER) if not osrel: osrel = _DEFAULT_VER return osrel def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} defaults 99'.format(_cmd_quote(name)) else: cmd = 'update-rc.d {0} enable'.format(_cmd_quote(name)) try: if int(osmajor) >= 6: cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd except ValueError: osrel = _osrel() if osrel == 'testing/unstable' or osrel == 'unstable' or osrel.endswith("/sid"): cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd return not __salt__['cmd.retcode'](cmd, python_shell=True) def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} remove'.format(name) else: cmd = 'update-rc.d {0} disable'.format(name) return not __salt__['cmd.retcode'](cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return name in get_enabled() def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return name in get_disabled()
saltstack/salt
salt/modules/debian_service.py
get_all
python
def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = set() lines = glob.glob('/etc/init.d/*') for line in lines: service = line.split('/etc/init.d/')[1] # Remove README. If it's an enabled service, it will be added back in. if service != 'README': ret.add(service) return sorted(ret | set(get_enabled()))
Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L136-L153
[ "def get_enabled():\n '''\n Return a list of service that are enabled on boot\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_enabled\n '''\n prefix = '/etc/rc[S{0}].d/S'.format(_get_runlevel())\n ret = set()\n lines = glob.glob('{0}*'.format(prefix))\n for line in lines:\n ret.add(re.split(prefix + r'\\d+', line)[1])\n return sorted(ret)\n" ]
# -*- coding: utf-8 -*- ''' Service support for Debian systems (uses update-rc.d and /sbin/service) .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import glob import fnmatch import re # Import 3rd-party libs # pylint: disable=import-error from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: enable=import-error # Import salt libs import salt.utils.systemd __func_alias__ = { 'reload_': 'reload' } # Define the module's virtual name __virtualname__ = 'service' log = logging.getLogger(__name__) _DEFAULT_VER = '7.0.0' def __virtual__(): ''' Only work on Debian and when systemd isn't running ''' if __grains__['os'] in ('Debian', 'Raspbian', 'Devuan', 'NILinuxRT') and not salt.utils.systemd.booted(__context__): return __virtualname__ else: return (False, 'The debian_service module could not be loaded: ' 'unsupported OS family and/or systemd running.') def _service_cmd(*args): osmajor = _osrel()[0] if osmajor < '6': cmd = '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) else: cmd = 'service {0} {1}'.format(args[0], ' '.join(args[1:])) return cmd def _get_runlevel(): ''' returns the current runlevel ''' out = __salt__['cmd.run']('runlevel') # unknown can be returned while inside a container environment, since # this is due to a lack of init, it should be safe to assume runlevel # 2, which is Debian's default. If not, all service related states # will throw an out of range exception here which will cause # other functions to fail. if 'unknown' in out: return '2' else: return out.split()[1] def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' prefix = '/etc/rc[S{0}].d/S'.format(_get_runlevel()) ret = set() lines = glob.glob('{0}*'.format(prefix)) for line in lines: ret.add(re.split(prefix + r'\d+', line)[1]) return sorted(ret) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return sorted(set(get_all()) - set(get_enabled())) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' return name in get_all() def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return name not in get_all() def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not __salt__['cmd.retcode'](cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not __salt__['cmd.retcode'](cmd) def force_reload(name): ''' Force-reload the named service CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' cmd = _service_cmd(name, 'force-reload') return not __salt__['cmd.retcode'](cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not __salt__['cmd.retcode'](cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def _osrel(): osrel = __grains__.get('osrelease', _DEFAULT_VER) if not osrel: osrel = _DEFAULT_VER return osrel def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} defaults 99'.format(_cmd_quote(name)) else: cmd = 'update-rc.d {0} enable'.format(_cmd_quote(name)) try: if int(osmajor) >= 6: cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd except ValueError: osrel = _osrel() if osrel == 'testing/unstable' or osrel == 'unstable' or osrel.endswith("/sid"): cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd return not __salt__['cmd.retcode'](cmd, python_shell=True) def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} remove'.format(name) else: cmd = 'update-rc.d {0} disable'.format(name) return not __salt__['cmd.retcode'](cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return name in get_enabled() def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return name in get_disabled()
saltstack/salt
salt/modules/debian_service.py
enable
python
def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} defaults 99'.format(_cmd_quote(name)) else: cmd = 'update-rc.d {0} enable'.format(_cmd_quote(name)) try: if int(osmajor) >= 6: cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd except ValueError: osrel = _osrel() if osrel == 'testing/unstable' or osrel == 'unstable' or osrel.endswith("/sid"): cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd return not __salt__['cmd.retcode'](cmd, python_shell=True)
Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L273-L295
[ "def _osrel():\n osrel = __grains__.get('osrelease', _DEFAULT_VER)\n if not osrel:\n osrel = _DEFAULT_VER\n return osrel\n" ]
# -*- coding: utf-8 -*- ''' Service support for Debian systems (uses update-rc.d and /sbin/service) .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import glob import fnmatch import re # Import 3rd-party libs # pylint: disable=import-error from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: enable=import-error # Import salt libs import salt.utils.systemd __func_alias__ = { 'reload_': 'reload' } # Define the module's virtual name __virtualname__ = 'service' log = logging.getLogger(__name__) _DEFAULT_VER = '7.0.0' def __virtual__(): ''' Only work on Debian and when systemd isn't running ''' if __grains__['os'] in ('Debian', 'Raspbian', 'Devuan', 'NILinuxRT') and not salt.utils.systemd.booted(__context__): return __virtualname__ else: return (False, 'The debian_service module could not be loaded: ' 'unsupported OS family and/or systemd running.') def _service_cmd(*args): osmajor = _osrel()[0] if osmajor < '6': cmd = '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) else: cmd = 'service {0} {1}'.format(args[0], ' '.join(args[1:])) return cmd def _get_runlevel(): ''' returns the current runlevel ''' out = __salt__['cmd.run']('runlevel') # unknown can be returned while inside a container environment, since # this is due to a lack of init, it should be safe to assume runlevel # 2, which is Debian's default. If not, all service related states # will throw an out of range exception here which will cause # other functions to fail. if 'unknown' in out: return '2' else: return out.split()[1] def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' prefix = '/etc/rc[S{0}].d/S'.format(_get_runlevel()) ret = set() lines = glob.glob('{0}*'.format(prefix)) for line in lines: ret.add(re.split(prefix + r'\d+', line)[1]) return sorted(ret) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return sorted(set(get_all()) - set(get_enabled())) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' return name in get_all() def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return name not in get_all() def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = set() lines = glob.glob('/etc/init.d/*') for line in lines: service = line.split('/etc/init.d/')[1] # Remove README. If it's an enabled service, it will be added back in. if service != 'README': ret.add(service) return sorted(ret | set(get_enabled())) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not __salt__['cmd.retcode'](cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not __salt__['cmd.retcode'](cmd) def force_reload(name): ''' Force-reload the named service CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' cmd = _service_cmd(name, 'force-reload') return not __salt__['cmd.retcode'](cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not __salt__['cmd.retcode'](cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def _osrel(): osrel = __grains__.get('osrelease', _DEFAULT_VER) if not osrel: osrel = _DEFAULT_VER return osrel def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} remove'.format(name) else: cmd = 'update-rc.d {0} disable'.format(name) return not __salt__['cmd.retcode'](cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return name in get_enabled() def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return name in get_disabled()
saltstack/salt
salt/modules/debian_service.py
disable
python
def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} remove'.format(name) else: cmd = 'update-rc.d {0} disable'.format(name) return not __salt__['cmd.retcode'](cmd)
Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_service.py#L298-L313
[ "def _osrel():\n osrel = __grains__.get('osrelease', _DEFAULT_VER)\n if not osrel:\n osrel = _DEFAULT_VER\n return osrel\n" ]
# -*- coding: utf-8 -*- ''' Service support for Debian systems (uses update-rc.d and /sbin/service) .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import glob import fnmatch import re # Import 3rd-party libs # pylint: disable=import-error from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: enable=import-error # Import salt libs import salt.utils.systemd __func_alias__ = { 'reload_': 'reload' } # Define the module's virtual name __virtualname__ = 'service' log = logging.getLogger(__name__) _DEFAULT_VER = '7.0.0' def __virtual__(): ''' Only work on Debian and when systemd isn't running ''' if __grains__['os'] in ('Debian', 'Raspbian', 'Devuan', 'NILinuxRT') and not salt.utils.systemd.booted(__context__): return __virtualname__ else: return (False, 'The debian_service module could not be loaded: ' 'unsupported OS family and/or systemd running.') def _service_cmd(*args): osmajor = _osrel()[0] if osmajor < '6': cmd = '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) else: cmd = 'service {0} {1}'.format(args[0], ' '.join(args[1:])) return cmd def _get_runlevel(): ''' returns the current runlevel ''' out = __salt__['cmd.run']('runlevel') # unknown can be returned while inside a container environment, since # this is due to a lack of init, it should be safe to assume runlevel # 2, which is Debian's default. If not, all service related states # will throw an out of range exception here which will cause # other functions to fail. if 'unknown' in out: return '2' else: return out.split()[1] def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' prefix = '/etc/rc[S{0}].d/S'.format(_get_runlevel()) ret = set() lines = glob.glob('{0}*'.format(prefix)) for line in lines: ret.add(re.split(prefix + r'\d+', line)[1]) return sorted(ret) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return sorted(set(get_all()) - set(get_enabled())) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' return name in get_all() def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return name not in get_all() def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = set() lines = glob.glob('/etc/init.d/*') for line in lines: service = line.split('/etc/init.d/')[1] # Remove README. If it's an enabled service, it will be added back in. if service != 'README': ret.add(service) return sorted(ret | set(get_enabled())) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not __salt__['cmd.retcode'](cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not __salt__['cmd.retcode'](cmd) def force_reload(name): ''' Force-reload the named service CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' cmd = _service_cmd(name, 'force-reload') return not __salt__['cmd.retcode'](cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not __salt__['cmd.retcode'](cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def _osrel(): osrel = __grains__.get('osrelease', _DEFAULT_VER) if not osrel: osrel = _DEFAULT_VER return osrel def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' osmajor = _osrel()[0] if osmajor < '6': cmd = 'update-rc.d -f {0} defaults 99'.format(_cmd_quote(name)) else: cmd = 'update-rc.d {0} enable'.format(_cmd_quote(name)) try: if int(osmajor) >= 6: cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd except ValueError: osrel = _osrel() if osrel == 'testing/unstable' or osrel == 'unstable' or osrel.endswith("/sid"): cmd = 'insserv {0} && '.format(_cmd_quote(name)) + cmd return not __salt__['cmd.retcode'](cmd, python_shell=True) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return name in get_enabled() def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return name in get_disabled()
saltstack/salt
salt/modules/keystone.py
_get_kwargs
python
def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs
get connection args
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L94-L135
[ "def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
api_version
python
def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None
Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L138-L154
[ "def _get_kwargs(profile=None, **connection_args):\n '''\n get connection args\n '''\n if profile:\n prefix = profile + \":keystone.\"\n else:\n prefix = \"keystone.\"\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n\n user = get('user', 'admin')\n password = get('password', 'ADMIN')\n tenant = get('tenant', 'admin')\n tenant_id = get('tenant_id')\n auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/')\n insecure = get('insecure', False)\n token = get('token')\n endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0')\n user_domain_name = get('user_domain_name', 'Default')\n project_domain_name = get('project_domain_name', 'Default')\n if token:\n kwargs = {'token': token,\n 'endpoint': endpoint}\n else:\n kwargs = {'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'tenant_id': tenant_id,\n 'auth_url': auth_url,\n 'user_domain_name': user_domain_name,\n 'project_domain_name': project_domain_name}\n # 'insecure' keyword not supported by all v2.0 keystone clients\n # this ensures it's only passed in when defined\n if insecure:\n kwargs['insecure'] = True\n return kwargs\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
auth
python
def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl
Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L157-L192
[ "def _get_kwargs(profile=None, **connection_args):\n '''\n get connection args\n '''\n if profile:\n prefix = profile + \":keystone.\"\n else:\n prefix = \"keystone.\"\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n\n user = get('user', 'admin')\n password = get('password', 'ADMIN')\n tenant = get('tenant', 'admin')\n tenant_id = get('tenant_id')\n auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/')\n insecure = get('insecure', False)\n token = get('token')\n endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0')\n user_domain_name = get('user_domain_name', 'Default')\n project_domain_name = get('project_domain_name', 'Default')\n if token:\n kwargs = {'token': token,\n 'endpoint': endpoint}\n else:\n kwargs = {'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'tenant_id': tenant_id,\n 'auth_url': auth_url,\n 'user_domain_name': user_domain_name,\n 'project_domain_name': project_domain_name}\n # 'insecure' keyword not supported by all v2.0 keystone clients\n # this ensures it's only passed in when defined\n if insecure:\n kwargs['insecure'] = True\n return kwargs\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
ec2_credentials_create
python
def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id}
Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L195-L229
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def user_get(user_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific users (keystone user-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for user in kstone.users.list():\n if user.name == name:\n user_id = user.id\n break\n if not user_id:\n return {'Error': 'Unable to resolve user id'}\n try:\n user = kstone.users.get(user_id)\n except keystoneclient.exceptions.NotFound:\n msg = 'Could not find user \\'{0}\\''.format(user_id)\n log.error(msg)\n return {'Error': msg}\n\n ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user)\n if not value.startswith('_') and\n isinstance(getattr(user, value, None), (six.string_types, dict, bool)))\n\n tenant_id = getattr(user, 'tenantId', None)\n if tenant_id:\n ret[user.name]['tenant_id'] = tenant_id\n return ret\n", "def tenant_get(tenant_id=None, name=None, profile=None,\n **connection_args):\n '''\n Return a specific tenants (keystone tenant-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n\n if name:\n for tenant in getattr(kstone, _TENANTS, None).list():\n if tenant.name == name:\n tenant_id = tenant.id\n break\n if not tenant_id:\n return {'Error': 'Unable to resolve tenant id'}\n tenant = getattr(kstone, _TENANTS, None).get(tenant_id)\n ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant)\n if not value.startswith('_') and\n isinstance(getattr(tenant, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
ec2_credentials_delete
python
def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id)
Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L232-L255
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def user_get(user_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific users (keystone user-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for user in kstone.users.list():\n if user.name == name:\n user_id = user.id\n break\n if not user_id:\n return {'Error': 'Unable to resolve user id'}\n try:\n user = kstone.users.get(user_id)\n except keystoneclient.exceptions.NotFound:\n msg = 'Could not find user \\'{0}\\''.format(user_id)\n log.error(msg)\n return {'Error': msg}\n\n ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user)\n if not value.startswith('_') and\n isinstance(getattr(user, value, None), (six.string_types, dict, bool)))\n\n tenant_id = getattr(user, 'tenantId', None)\n if tenant_id:\n ret[user.name]['tenant_id'] = tenant_id\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
ec2_credentials_get
python
def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret
Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L258-L288
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
ec2_credentials_list
python
def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret
Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L291-L318
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
endpoint_get
python
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'}
Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L321-L349
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def service_list(profile=None, **connection_args):\n '''\n Return a list of available services (keystone services-list)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.service_list\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n for service in kstone.services.list():\n ret[service.name] = dict((value, getattr(service, value)) for value in dir(service)\n if not value.startswith('_') and\n isinstance(getattr(service, value), (six.string_types, dict, bool)))\n return ret\n", "def endpoint_list(profile=None, **connection_args):\n '''\n Return a list of available endpoints (keystone endpoints-list)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.endpoint_list\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n\n for endpoint in kstone.endpoints.list():\n ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint)\n if not value.startswith('_') and\n isinstance(getattr(endpoint, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
endpoint_list
python
def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret
Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L352-L369
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
endpoint_create
python
def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args)
Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L372-L402
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def endpoint_get(service, region=None, profile=None, interface=None, **connection_args):\n '''\n Return a specific endpoint (keystone endpoint-get)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'v2' keystone.endpoint_get nova [region=RegionOne]\n\n salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne]\n '''\n auth(profile, **connection_args)\n services = service_list(profile, **connection_args)\n if service not in services:\n return {'Error': 'Could not find the specified service'}\n service_id = services[service]['id']\n endpoints = endpoint_list(profile, **connection_args)\n\n e = [_f for _f in [e\n if e['service_id'] == service_id and\n (e['region'] == region if region else True) and\n (e['interface'] == interface if interface else True)\n else None for e in endpoints.values()] if _f]\n if len(e) > 1:\n return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)}\n if len(e) == 1:\n return e[0]\n return {'Error': 'Could not find endpoint for the specified service'}\n", "def service_get(service_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific services (keystone service-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.service_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for service in kstone.services.list():\n if service.name == name:\n service_id = service.id\n break\n if not service_id:\n return {'Error': 'Unable to resolve service id'}\n service = kstone.services.get(service_id)\n ret[service.name] = dict((value, getattr(service, value)) for value in dir(service)\n if not value.startswith('_') and\n isinstance(getattr(service, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
endpoint_delete
python
def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True
Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L405-L424
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def endpoint_get(service, region=None, profile=None, interface=None, **connection_args):\n '''\n Return a specific endpoint (keystone endpoint-get)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'v2' keystone.endpoint_get nova [region=RegionOne]\n\n salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne]\n '''\n auth(profile, **connection_args)\n services = service_list(profile, **connection_args)\n if service not in services:\n return {'Error': 'Could not find the specified service'}\n service_id = services[service]['id']\n endpoints = endpoint_list(profile, **connection_args)\n\n e = [_f for _f in [e\n if e['service_id'] == service_id and\n (e['region'] == region if region else True) and\n (e['interface'] == interface if interface else True)\n else None for e in endpoints.values()] if _f]\n if len(e) > 1:\n return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)}\n if len(e) == 1:\n return e[0]\n return {'Error': 'Could not find endpoint for the specified service'}\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
role_create
python
def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args)
Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L427-L442
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def role_get(role_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific roles (keystone role-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.role_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for role in kstone.roles.list():\n if role.name == name:\n role_id = role.id\n break\n if not role_id:\n return {'Error': 'Unable to resolve role id'}\n role = kstone.roles.get(role_id)\n\n ret[role.name] = {'id': role.id,\n 'name': role.name}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
role_delete
python
def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret
Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L445-L475
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
role_get
python
def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret
Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L478-L503
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
role_list
python
def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret
Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L506-L522
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
service_create
python
def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args)
Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L525-L539
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def service_get(service_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific services (keystone service-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.service_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for service in kstone.services.list():\n if service.name == name:\n service_id = service.id\n break\n if not service_id:\n return {'Error': 'Unable to resolve service id'}\n service = kstone.services.get(service_id)\n ret[service.name] = dict((value, getattr(service, value)) for value in dir(service)\n if not value.startswith('_') and\n isinstance(getattr(service, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
service_delete
python
def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id)
Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L542-L558
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def service_get(service_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific services (keystone service-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.service_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for service in kstone.services.list():\n if service.name == name:\n service_id = service.id\n break\n if not service_id:\n return {'Error': 'Unable to resolve service id'}\n service = kstone.services.get(service_id)\n ret[service.name] = dict((value, getattr(service, value)) for value in dir(service)\n if not value.startswith('_') and\n isinstance(getattr(service, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
service_get
python
def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret
Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L561-L586
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
service_list
python
def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret
Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L589-L605
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
tenant_create
python
def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args)
Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L608-L622
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def tenant_get(tenant_id=None, name=None, profile=None,\n **connection_args):\n '''\n Return a specific tenants (keystone tenant-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n\n if name:\n for tenant in getattr(kstone, _TENANTS, None).list():\n if tenant.name == name:\n tenant_id = tenant.id\n break\n if not tenant_id:\n return {'Error': 'Unable to resolve tenant id'}\n tenant = getattr(kstone, _TENANTS, None).get(tenant_id)\n ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant)\n if not value.startswith('_') and\n isinstance(getattr(tenant, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
tenant_delete
python
def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret
Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L661-L686
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
project_delete
python
def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False
Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L689-L718
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args):\n '''\n Delete a tenant (keystone tenant-delete)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_delete name=demo\n '''\n kstone = auth(profile, **connection_args)\n if name:\n for tenant in getattr(kstone, _TENANTS, None).list():\n if tenant.name == name:\n tenant_id = tenant.id\n break\n if not tenant_id:\n return {'Error': 'Unable to resolve tenant id'}\n getattr(kstone, _TENANTS, None).delete(tenant_id)\n ret = 'Tenant ID {0} deleted'.format(tenant_id)\n if name:\n\n ret += ' ({0})'.format(name)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
tenant_get
python
def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret
Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L721-L748
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
project_get
python
def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False
Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L751-L781
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def tenant_get(tenant_id=None, name=None, profile=None,\n **connection_args):\n '''\n Return a specific tenants (keystone tenant-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n\n if name:\n for tenant in getattr(kstone, _TENANTS, None).list():\n if tenant.name == name:\n tenant_id = tenant.id\n break\n if not tenant_id:\n return {'Error': 'Unable to resolve tenant id'}\n tenant = getattr(kstone, _TENANTS, None).get(tenant_id)\n ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant)\n if not value.startswith('_') and\n isinstance(getattr(tenant, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
tenant_list
python
def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret
Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L784-L801
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
project_list
python
def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False
Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L804-L826
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def tenant_list(profile=None, **connection_args):\n '''\n Return a list of available tenants (keystone tenants-list)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.tenant_list\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n\n for tenant in getattr(kstone, _TENANTS, None).list():\n ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant)\n if not value.startswith('_') and\n isinstance(getattr(tenant, value), (six.string_types, dict, bool)))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
tenant_update
python
def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool)))
Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L829-L864
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
project_update
python
def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False
Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L867-L907
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def tenant_update(tenant_id=None, name=None, description=None,\n enabled=None, profile=None, **connection_args):\n '''\n Update a tenant's information (keystone tenant-update)\n The following fields may be updated: name, description, enabled.\n Can only update name if targeting by ID\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.tenant_update name=admin enabled=True\n salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com\n '''\n kstone = auth(profile, **connection_args)\n\n if not tenant_id:\n for tenant in getattr(kstone, _TENANTS, None).list():\n if tenant.name == name:\n tenant_id = tenant.id\n break\n if not tenant_id:\n return {'Error': 'Unable to resolve tenant id'}\n\n tenant = getattr(kstone, _TENANTS, None).get(tenant_id)\n if not name:\n name = tenant.name\n if not description:\n description = tenant.description\n if enabled is None:\n enabled = tenant.enabled\n updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled)\n\n return dict((value, getattr(updated, value)) for value in dir(updated)\n if not value.startswith('_') and\n isinstance(getattr(updated, value), (six.string_types, dict, bool)))\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
token_get
python
def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']}
Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L910-L925
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_list
python
def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret
Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L928-L947
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_get
python
def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret
Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L950-L985
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_create
python
def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args)
Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L988-L1017
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def user_get(user_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific users (keystone user-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for user in kstone.users.list():\n if user.name == name:\n user_id = user.id\n break\n if not user_id:\n return {'Error': 'Unable to resolve user id'}\n try:\n user = kstone.users.get(user_id)\n except keystoneclient.exceptions.NotFound:\n msg = 'Could not find user \\'{0}\\''.format(user_id)\n log.error(msg)\n return {'Error': msg}\n\n ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user)\n if not value.startswith('_') and\n isinstance(getattr(user, value, None), (six.string_types, dict, bool)))\n\n tenant_id = getattr(user, 'tenantId', None)\n if tenant_id:\n ret[user.name]['tenant_id'] = tenant_id\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_delete
python
def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret
Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1020-L1045
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_update
python
def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret
Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1048-L1109
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_verify_password
python
def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True
Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1112-L1157
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_password_update
python
def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret
Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1160-L1189
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_role_add
python
def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant)
Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1192-L1247
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n", "def user_get(user_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific users (keystone user-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.user_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for user in kstone.users.list():\n if user.name == name:\n user_id = user.id\n break\n if not user_id:\n return {'Error': 'Unable to resolve user id'}\n try:\n user = kstone.users.get(user_id)\n except keystoneclient.exceptions.NotFound:\n msg = 'Could not find user \\'{0}\\''.format(user_id)\n log.error(msg)\n return {'Error': msg}\n\n ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user)\n if not value.startswith('_') and\n isinstance(getattr(user, value, None), (six.string_types, dict, bool)))\n\n tenant_id = getattr(user, 'tenantId', None)\n if tenant_id:\n ret[user.name]['tenant_id'] = tenant_id\n return ret\n", "def tenant_get(tenant_id=None, name=None, profile=None,\n **connection_args):\n '''\n Return a specific tenants (keystone tenant-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.tenant_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n\n if name:\n for tenant in getattr(kstone, _TENANTS, None).list():\n if tenant.name == name:\n tenant_id = tenant.id\n break\n if not tenant_id:\n return {'Error': 'Unable to resolve tenant id'}\n tenant = getattr(kstone, _TENANTS, None).get(tenant_id)\n ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant)\n if not value.startswith('_') and\n isinstance(getattr(tenant, value), (six.string_types, dict, bool)))\n return ret\n", "def role_get(role_id=None, name=None, profile=None, **connection_args):\n '''\n Return a specific roles (keystone role-get)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082\n salt '*' keystone.role_get name=nova\n '''\n kstone = auth(profile, **connection_args)\n ret = {}\n if name:\n for role in kstone.roles.list():\n if role.name == name:\n role_id = role.id\n break\n if not role_id:\n return {'Error': 'Unable to resolve role id'}\n role = kstone.roles.get(role_id)\n\n ret[role.name] = {'id': role.id,\n 'name': role.name}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
user_role_list
python
def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret
Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1307-L1353
[ "def auth(profile=None, **connection_args):\n '''\n Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' keystone.auth\n '''\n __utils__['versions.warn_until'](\n 'Neon',\n (\n 'The keystone module has been deprecated and will be removed in {version}. '\n 'Please update to using the keystoneng module'\n ),\n )\n kwargs = _get_kwargs(profile=profile, **connection_args)\n\n disc = discover.Discover(auth_url=kwargs['auth_url'])\n v2_auth_url = disc.url_for('v2.0')\n v3_auth_url = disc.url_for('v3.0')\n if v3_auth_url:\n global _OS_IDENTITY_API_VERSION\n global _TENANTS\n _OS_IDENTITY_API_VERSION = 3\n _TENANTS = 'projects'\n kwargs['auth_url'] = v3_auth_url\n else:\n kwargs['auth_url'] = v2_auth_url\n kwargs.pop('user_domain_name')\n kwargs.pop('project_domain_name')\n auth = generic.Password(**kwargs)\n sess = session.Session(auth=auth)\n ks_cl = disc.create_client(session=sess)\n return ks_cl\n" ]
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/modules/keystone.py
_item_list
python
def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in kstone.items.list(): ret.append(item.__dict__) # ret[item.name] = { # 'id': item.id, # 'name': item.name, # } return ret
Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1356-L1375
null
# -*- coding: utf-8 -*- ''' Module for handling openstack keystone calls. :optdepends: - keystoneclient Python adapter :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' OR (for token based authentication) .. code-block:: yaml keystone.token: 'ADMIN' keystone.endpoint: 'http://127.0.0.1:35357/v2.0' If configuration for multiple openstack accounts is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.tenant_id: f80919baedab48ec8931f200c65a50df keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the keystone functions can make use of a configuration profile by declaring it explicitly. For example: .. code-block:: bash salt '*' keystone.tenant_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.http # Import 3rd-party libs from salt.ext import six HAS_KEYSTONE = False try: # pylint: disable=import-error from keystoneclient.v2_0 import client import keystoneclient.exceptions HAS_KEYSTONE = True from keystoneclient.v3 import client as client3 from keystoneclient import discover from keystoneauth1 import session from keystoneauth1.identity import generic # pylint: enable=import-error except ImportError: pass _OS_IDENTITY_API_VERSION = 2 _TENANTS = 'tenants' log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if keystone is installed on this minion. ''' if HAS_KEYSTONE: return 'keystone' return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.') __opts__ = {} def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', 'ADMIN') tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0/') insecure = get('insecure', False) token = get('token') endpoint = get('endpoint', 'http://127.0.0.1:35357/v2.0') user_domain_name = get('user_domain_name', 'Default') project_domain_name = get('project_domain_name', 'Default') if token: kwargs = {'token': token, 'endpoint': endpoint} else: kwargs = {'username': user, 'password': password, 'tenant_name': tenant, 'tenant_id': tenant_id, 'auth_url': auth_url, 'user_domain_name': user_domain_name, 'project_domain_name': project_domain_name} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True return kwargs def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None)) try: return salt.utils.http.query(auth_url, decode=True, decode_type='json', verify_ssl=False)['dict']['version']['id'] except KeyError: return None def auth(profile=None, **connection_args): ''' Set up keystone credentials. Only intended to be used within Keystone-enabled modules. CLI Example: .. code-block:: bash salt '*' keystone.auth ''' __utils__['versions.warn_until']( 'Neon', ( 'The keystone module has been deprecated and will be removed in {version}. ' 'Please update to using the keystoneng module' ), ) kwargs = _get_kwargs(profile=profile, **connection_args) disc = discover.Discover(auth_url=kwargs['auth_url']) v2_auth_url = disc.url_for('v2.0') v3_auth_url = disc.url_for('v3.0') if v3_auth_url: global _OS_IDENTITY_API_VERSION global _TENANTS _OS_IDENTITY_API_VERSION = 3 _TENANTS = 'projects' kwargs['auth_url'] = v3_auth_url else: kwargs['auth_url'] = v2_auth_url kwargs.pop('user_domain_name') kwargs.pop('project_domain_name') auth = generic.Password(**kwargs) sess = session.Session(auth=auth) ks_cl = disc.create_client(session=sess) return ks_cl def ec2_credentials_create(user_id=None, name=None, tenant_id=None, tenant=None, profile=None, **connection_args): ''' Create EC2-compatible credentials for user per tenant CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_create name=admin tenant=admin salt '*' keystone.ec2_credentials_create \ user_id=c965f79c4f864eaaa9c3b41904e67082 \ tenant_id=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=profile, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant]['id'] if not tenant_id: return {'Error': 'Could not resolve Tenant ID'} newec2 = kstone.ec2.create(user_id, tenant_id) return {'access': newec2.access, 'secret': newec2.secret, 'tenant_id': newec2.tenant_id, 'user_id': newec2.user_id} def ec2_credentials_delete(user_id=None, name=None, access_key=None, profile=None, **connection_args): ''' Delete EC2-compatible credentials CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_delete \ 860f8c2c38ca4fab989f9bc56a061a64 access_key=5f66d2f24f604b8bb9cd28886106f442 salt '*' keystone.ec2_credentials_delete name=admin \ access_key=5f66d2f24f604b8bb9cd28886106f442 ''' kstone = auth(profile, **connection_args) if name: user_id = user_get(name=name, profile=None, **connection_args)[name]['id'] if not user_id: return {'Error': 'Could not resolve User ID'} kstone.ec2.delete(user_id, access_key) return 'ec2 key "{0}" deleted under user id "{1}"'.format(access_key, user_id) def ec2_credentials_get(user_id=None, name=None, access=None, profile=None, **connection_args): ''' Return ec2_credentials for a user (keystone ec2-credentials-get) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370 salt '*' keystone.ec2_credentials_get name=nova access=722787eb540849158668370dc627ec5f ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if not access: return {'Error': 'Access key is required'} ec2_credentials = kstone.ec2.get(user_id=user_id, access=access, profile=profile, **connection_args) ret[ec2_credentials.user_id] = {'user_id': ec2_credentials.user_id, 'tenant': ec2_credentials.tenant_id, 'access': ec2_credentials.access, 'secret': ec2_credentials.secret} return ret def ec2_credentials_list(user_id=None, name=None, profile=None, **connection_args): ''' Return a list of ec2_credentials for a specific user (keystone ec2-credentials-list) CLI Examples: .. code-block:: bash salt '*' keystone.ec2_credentials_list 298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list user_id=298ce377245c4ec9b70e1c639c89e654 salt '*' keystone.ec2_credentials_list name=jack ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} for ec2_credential in kstone.ec2.list(user_id): ret[ec2_credential.user_id] = {'user_id': ec2_credential.user_id, 'tenant_id': ec2_credential.tenant_id, 'access': ec2_credential.access, 'secret': ec2_credential.secret} return ret def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] ''' auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {'Error': 'Could not find the specified service'} service_id = services[service]['id'] endpoints = endpoint_list(profile, **connection_args) e = [_f for _f in [e if e['service_id'] == service_id and (e['region'] == region if region else True) and (e['interface'] == interface if interface else True) else None for e in endpoints.values()] if _f] if len(e) > 1: return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)} if len(e) == 1: return e[0] return {'Error': 'Could not find endpoint for the specified service'} def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.list(): ret[endpoint.id] = dict((value, getattr(endpoint, value)) for value in dir(endpoint) if not value.startswith('_') and isinstance(getattr(endpoint, value), (six.string_types, dict, bool))) return ret def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne' ''' kstone = auth(profile, **connection_args) keystone_service = service_get(name=service, profile=profile, **connection_args) if not keystone_service or 'Error' in keystone_service: return {'Error': 'Could not find the specified service'} if _OS_IDENTITY_API_VERSION > 2: kstone.endpoints.create(service=keystone_service[service]['id'], region_id=region, url=url, interface=interface) else: kstone.endpoints.create(region=region, service_id=keystone_service[service]['id'], publicurl=publicurl, adminurl=adminurl, internalurl=internalurl) return endpoint_get(service, region, profile, interface, **connection_args) def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=admin [region=RegionOne] ''' kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, region, profile, interface, **connection_args) if not endpoint or 'Error' in endpoint: return True def role_create(name, profile=None, **connection_args): ''' Create a named role. CLI Example: .. code-block:: bash salt '*' keystone.role_create admin ''' kstone = auth(profile, **connection_args) if 'Error' not in role_get(name=name, profile=profile, **connection_args): return {'Error': 'Role "{0}" already exists'.format(name)} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) def role_delete(role_id=None, name=None, profile=None, **connection_args): ''' Delete a role (keystone role-delete) CLI Examples: .. code-block:: bash salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_delete name=admin ''' kstone = auth(profile, **connection_args) if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) kstone.roles.delete(role) ret = 'Role ID {0} deleted'.format(role_id) if name: ret += ' ({0})'.format(name) return ret def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for role in kstone.roles.list(): if role.name == name: role_id = role.id break if not role_id: return {'Error': 'Unable to resolve role id'} role = kstone.roles.get(role_id) ret[role.name] = {'id': role.id, 'name': role.name} return ret def role_list(profile=None, **connection_args): ''' Return a list of available roles (keystone role-list) CLI Example: .. code-block:: bash salt '*' keystone.role_list ''' kstone = auth(profile, **connection_args) ret = {} for role in kstone.roles.list(): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) return ret def service_create(name, service_type, description=None, profile=None, **connection_args): ''' Add service to Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_create nova compute \ 'OpenStack Compute Service' ''' kstone = auth(profile, **connection_args) service = kstone.services.create(name, service_type, description=description) return service_get(service.id, profile=profile, **connection_args) def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' kstone = auth(profile, **connection_args) if name: service_id = service_get(name=name, profile=profile, **connection_args)[name]['id'] kstone.services.delete(service_id) return 'Keystone service ID "{0}" deleted'.format(service_id) def service_get(service_id=None, name=None, profile=None, **connection_args): ''' Return a specific services (keystone service-get) CLI Examples: .. code-block:: bash salt '*' keystone.service_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get service_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for service in kstone.services.list(): if service.name == name: service_id = service.id break if not service_id: return {'Error': 'Unable to resolve service id'} service = kstone.services.get(service_id) ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def service_list(profile=None, **connection_args): ''' Return a list of available services (keystone services-list) CLI Example: .. code-block:: bash salt '*' keystone.service_list ''' kstone = auth(profile, **connection_args) ret = {} for service in kstone.services.list(): ret[service.name] = dict((value, getattr(service, value)) for value in dir(service) if not value.startswith('_') and isinstance(getattr(service, value), (six.string_types, dict, bool))) return ret def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args) def project_create(name, domain, description=None, enabled=True, profile=None, **connection_args): ''' Create a keystone project. Overrides keystone tenant_create form api V2. For keystone api V3. .. versionadded:: 2016.11.0 name The project name, which must be unique within the owning domain. domain The domain name. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_create nova default description='Nova Compute Project' salt '*' keystone.project_create test default enabled=False ''' kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name=name, domain=domain, description=description, enabled=enabled) return tenant_get(new.id, profile=profile, **connection_args) def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): ''' Delete a tenant (keystone tenant-delete) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_delete name=demo ''' kstone = auth(profile, **connection_args) if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} getattr(kstone, _TENANTS, None).delete(tenant_id) ret = 'Tenant ID {0} deleted'.format(tenant_id) if name: ret += ' ({0})'.format(name) return ret def project_delete(project_id=None, name=None, profile=None, **connection_args): ''' Delete a project (keystone project-delete). Overrides keystone tenant-delete form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_delete name=demo ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get project_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.project_get name=nova ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_get(tenant_id=project_id, name=name, profile=None, **connection_args) else: return False def tenant_list(profile=None, **connection_args): ''' Return a list of available tenants (keystone tenants-list) CLI Example: .. code-block:: bash salt '*' keystone.tenant_list ''' kstone = auth(profile, **connection_args) ret = {} for tenant in getattr(kstone, _TENANTS, None).list(): ret[tenant.name] = dict((value, getattr(tenant, value)) for value in dir(tenant) if not value.startswith('_') and isinstance(getattr(tenant, value), (six.string_types, dict, bool))) return ret def project_list(profile=None, **connection_args): ''' Return a list of available projects (keystone projects-list). Overrides keystone tenants-list form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 profile Configuration profile - if configuration for multiple openstack accounts required. CLI Example: .. code-block:: bash salt '*' keystone.project_list ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_list(profile, **connection_args) else: return False def tenant_update(tenant_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone tenant-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID CLI Examples: .. code-block:: bash salt '*' keystone.tenant_update name=admin enabled=True salt '*' keystone.tenant_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' kstone = auth(profile, **connection_args) if not tenant_id: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id break if not tenant_id: return {'Error': 'Unable to resolve tenant id'} tenant = getattr(kstone, _TENANTS, None).get(tenant_id) if not name: name = tenant.name if not description: description = tenant.description if enabled is None: enabled = tenant.enabled updated = getattr(kstone, _TENANTS, None).update(tenant_id, name=name, description=description, enabled=enabled) return dict((value, getattr(updated, value)) for value in dir(updated) if not value.startswith('_') and isinstance(getattr(updated, value), (six.string_types, dict, bool))) def project_update(project_id=None, name=None, description=None, enabled=None, profile=None, **connection_args): ''' Update a tenant's information (keystone project-update) The following fields may be updated: name, description, enabled. Can only update name if targeting by ID Overrides keystone tenant_update form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project name, which must be unique within the owning domain. description The project description. enabled Enables or disables the project. profile Configuration profile - if configuration for multiple openstack accounts required. CLI Examples: .. code-block:: bash salt '*' keystone.project_update name=admin enabled=True salt '*' keystone.project_update c965f79c4f864eaaa9c3b41904e67082 name=admin email=admin@domain.com ''' auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: return tenant_update(tenant_id=project_id, name=name, description=description, enabled=enabled, profile=profile, **connection_args) else: return False def token_get(profile=None, **connection_args): ''' Return the configured tokens (keystone token-get) CLI Example: .. code-block:: bash salt '*' keystone.token_get c965f79c4f864eaaa9c3b41904e67082 ''' kstone = auth(profile, **connection_args) token = kstone.service_catalog.get_token() return {'id': token['id'], 'expires': token['expires'], 'user_id': token['user_id'], 'tenant_id': token['tenant_id']} def user_list(profile=None, **connection_args): ''' Return a list of available users (keystone user-list) CLI Example: .. code-block:: bash salt '*' keystone.user_list ''' kstone = auth(profile, **connection_args) ret = {} for user in kstone.users.list(): ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get name=nova ''' kstone = auth(profile, **connection_args) ret = {} if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: msg = 'Could not find user \'{0}\''.format(user_id) log.error(msg) return {'Error': msg} ret[user.name] = dict((value, getattr(user, value, None)) for value in dir(user) if not value.startswith('_') and isinstance(getattr(user, value, None), (six.string_types, dict, bool))) tenant_id = getattr(user, 'tenantId', None) if tenant_id: ret[user.name]['tenant_id'] = tenant_id return ret def user_create(name, password, email, tenant_id=None, enabled=True, profile=None, project_id=None, description=None, **connection_args): ''' Create a user (keystone user-create) CLI Examples: .. code-block:: bash salt '*' keystone.user_create name=jack password=zero email=jack@halloweentown.org \ tenant_id=a28a7b5a999a455f84b1f5210264375e enabled=True ''' kstone = auth(profile, **connection_args) if _OS_IDENTITY_API_VERSION > 2: if tenant_id and not project_id: project_id = tenant_id item = kstone.users.create(name=name, password=password, email=email, project_id=project_id, enabled=enabled, description=description) else: item = kstone.users.create(name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled) return user_get(item.id, profile=profile, **connection_args) def user_delete(user_id=None, name=None, profile=None, **connection_args): ''' Delete a user (keystone user-delete) CLI Examples: .. code-block:: bash salt '*' keystone.user_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete user_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_delete name=nova ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} kstone.users.delete(user_id) ret = 'User ID {0} deleted'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_update(user_id=None, name=None, email=None, enabled=None, tenant=None, profile=None, project=None, description=None, **connection_args): ''' Update a user's information (keystone user-update) The following fields may be updated: name, email, enabled, tenant. Because the name is one of the fields, a valid user id is required. CLI Examples: .. code-block:: bash salt '*' keystone.user_update user_id=c965f79c4f864eaaa9c3b41904e67082 name=newname salt '*' keystone.user_update c965f79c4f864eaaa9c3b41904e67082 name=newname email=newemail@domain.com ''' kstone = auth(profile, **connection_args) if not user_id: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} user = kstone.users.get(user_id) # Keep previous settings if not updating them if not name: name = user.name if not email: email = user.email if enabled is None: enabled = user.enabled if _OS_IDENTITY_API_VERSION > 2: if description is None: description = getattr(user, 'description', None) else: description = six.text_type(description) project_id = None if project: for proj in kstone.projects.list(): if proj.name == project: project_id = proj.id break if not project_id: project_id = getattr(user, 'project_id', None) kstone.users.update(user=user_id, name=name, email=email, enabled=enabled, description=description, project_id=project_id) else: kstone.users.update(user=user_id, name=name, email=email, enabled=enabled) tenant_id = None if tenant: for tnt in kstone.tenants.list(): if tnt.name == tenant: tenant_id = tnt.id break if tenant_id: kstone.users.update_tenant(user_id, tenant_id) ret = 'Info updated for user ID {0}'.format(user_id) return ret def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar ''' kstone = auth(profile, **connection_args) if 'connection_endpoint' in connection_args: auth_url = connection_args.get('connection_endpoint') else: auth_url_opt = 'keystone.auth_url' if __salt__['config.option']('keystone.token'): auth_url_opt = 'keystone.endpoint' if _OS_IDENTITY_API_VERSION > 2: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v3') else: auth_url = __salt__['config.option'](auth_url_opt, 'http://127.0.0.1:35357/v2.0') if user_id: for user in kstone.users.list(): if user.id == user_id: name = user.name break if not name: return {'Error': 'Unable to resolve user name'} kwargs = {'username': name, 'password': password, 'auth_url': auth_url} try: if _OS_IDENTITY_API_VERSION > 2: client3.Client(**kwargs) else: client.Client(**kwargs) except (keystoneclient.exceptions.Unauthorized, keystoneclient.exceptions.AuthorizationFailure): return False return True def user_password_update(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Update a user's password (keystone user-password-update) CLI Examples: .. code-block:: bash salt '*' keystone.user_password_update c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update user_id=c965f79c4f864eaaa9c3b41904e67082 password=12345 salt '*' keystone.user_password_update name=nova password=12345 ''' kstone = auth(profile, **connection_args) if name: for user in kstone.users.list(): if user.name == name: user_id = user.id break if not user_id: return {'Error': 'Unable to resolve user id'} if _OS_IDENTITY_API_VERSION > 2: kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) ret = 'Password updated for user ID {0}'.format(user_id) if name: ret += ' ({0})'.format(name) return ret def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_add \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_add user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id, profile=profile, **connection_args)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.grant(role_id, user=user_id, project=tenant_id) else: kstone.roles.add_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project' return ret_msg.format(role, user, tenant) def user_role_remove(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Remove role for user in tenant (keystone user-role-remove) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_remove \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b \ role_id=ce377245c4ec9b70e1c639c89e8cead4 salt '*' keystone.user_role_remove user=admin tenant=admin role=admin ''' kstone = auth(profile, **connection_args) if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant: tenant = project_name if user: user_id = user_get(name=user, profile=profile, **connection_args)[user].get('id') else: user = next(six.iterkeys(user_get(user_id, profile=profile, **connection_args)))['name'] if not user_id: return {'Error': 'Unable to resolve user id'} if tenant: tenant_id = tenant_get(name=tenant, profile=profile, **connection_args)[tenant].get('id') else: tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile, **connection_args)))['name'] if not tenant_id: return {'Error': 'Unable to resolve tenant/project id'} if role: role_id = role_get(name=role, profile=profile, **connection_args)[role]['id'] else: role = next(six.iterkeys(role_get(role_id)))['name'] if not role_id: return {'Error': 'Unable to resolve role id'} if _OS_IDENTITY_API_VERSION > 2: kstone.roles.revoke(role_id, user=user_id, project=tenant_id) else: kstone.roles.remove_user_role(user_id, role_id, tenant_id) ret_msg = '"{0}" role removed for user "{1}" under "{2}" tenant' return ret_msg.format(role, user, tenant) def user_role_list(user_id=None, tenant_id=None, user_name=None, tenant_name=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Return a list of available user_roles (keystone user-roles-list) CLI Examples: .. code-block:: bash salt '*' keystone.user_role_list \ user_id=298ce377245c4ec9b70e1c639c89e654 \ tenant_id=7167a092ece84bae8cead4bf9d15bb3b salt '*' keystone.user_role_list user_name=admin tenant_name=admin ''' kstone = auth(profile, **connection_args) ret = {} if project_id and not tenant_id: tenant_id = project_id elif project_name and not tenant_name: tenant_name = project_name if user_name: for user in kstone.users.list(): if user.name == user_name: user_id = user.id break if tenant_name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == tenant_name: tenant_id = tenant.id break if not user_id or not tenant_id: return {'Error': 'Unable to resolve user or tenant/project id'} if _OS_IDENTITY_API_VERSION > 2: for role in kstone.roles.list(user=user_id, project=tenant_id): ret[role.name] = dict((value, getattr(role, value)) for value in dir(role) if not value.startswith('_') and isinstance(getattr(role, value), (six.string_types, dict, bool))) else: for role in kstone.roles.roles_for_user(user=user_id, tenant=tenant_id): ret[role.name] = {'id': role.id, 'name': role.name, 'user_id': user_id, 'tenant_id': tenant_id} return ret # The following is a list of functions that need to be incorporated in the # keystone module. This list should be updated as functions are added. # # endpoint-create Create a new endpoint associated with a service # endpoint-delete Delete a service endpoint # discover Discover Keystone servers and show authentication # protocols and # bootstrap Grants a new role to a new user on a new tenant, after # creating each.
saltstack/salt
salt/roster/sshconfig.py
_get_ssh_config_file
python
def _get_ssh_config_file(opts): ''' :return: Path to the .ssh/config file - usually <home>/.ssh/config ''' ssh_config_file = opts.get('ssh_config_file') if not os.path.isfile(ssh_config_file): raise IOError('Cannot find SSH config file') if not os.access(ssh_config_file, os.R_OK): raise IOError('Cannot access SSH config file: {}'.format(ssh_config_file)) return ssh_config_file
:return: Path to the .ssh/config file - usually <home>/.ssh/config
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L33-L42
null
# -*- coding: utf-8 -*- ''' Parses roster entries out of Host directives from SSH config .. code-block:: bash salt-ssh --roster sshconfig '*' -r "echo hi" ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import collections import fnmatch import re # Import Salt libs import salt.utils.files import salt.utils.stringutils from salt.ext import six import logging log = logging.getLogger(__name__) _SSHConfRegex = collections.namedtuple('_SSHConfRegex', ['target_field', 'pattern']) _ROSTER_FIELDS = ( _SSHConfRegex(target_field='user', pattern=r'\s+User (.*)'), _SSHConfRegex(target_field='port', pattern=r'\s+Port (.*)'), _SSHConfRegex(target_field='priv', pattern=r'\s+IdentityFile (.*)'), ) def parse_ssh_config(lines): ''' Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster ''' # transform the list of individual lines into a list of sublists where each # sublist represents a single Host definition hosts = [] for line in lines: line = salt.utils.stringutils.to_unicode(line) if not line or line.startswith('#'): continue elif line.startswith('Host '): hosts.append([]) hosts[-1].append(line) # construct a dictionary of Host names to mapped roster properties targets = collections.OrderedDict() for host_data in hosts: target = collections.OrderedDict() hostnames = host_data[0].split()[1:] for line in host_data[1:]: for field in _ROSTER_FIELDS: match = re.match(field.pattern, line) if match: target[field.target_field] = match.group(1) for hostname in hostnames: targets[hostname] = target # apply matching for glob hosts wildcard_targets = [] non_wildcard_targets = [] for target in targets.keys(): if '*' in target or '?' in target: wildcard_targets.append(target) else: non_wildcard_targets.append(target) for pattern in wildcard_targets: for candidate in non_wildcard_targets: if fnmatch.fnmatch(candidate, pattern): targets[candidate].update(targets[pattern]) del targets[pattern] # finally, update the 'host' to refer to its declaration in the SSH config # so that its connection parameters can be utilized for target in targets: targets[target]['host'] = target return targets def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the flat yaml file, checks opts for location but defaults to /etc/salt/roster ''' ssh_config_file = _get_ssh_config_file(__opts__) with salt.utils.files.fopen(ssh_config_file, 'r') as fp: all_minions = parse_ssh_config([line.rstrip() for line in fp]) rmatcher = RosterMatcher(all_minions, tgt, tgt_type) matched = rmatcher.targets() return matched class RosterMatcher(object): ''' Matcher for the roster data structure ''' def __init__(self, raw, tgt, tgt_type): self.tgt = tgt self.tgt_type = tgt_type self.raw = raw def targets(self): ''' Execute the correct tgt_type routine and return ''' try: return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))() except AttributeError: return {} def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions def get_data(self, minion): ''' Return the configured ip ''' if isinstance(self.raw[minion], six.string_types): return {'host': self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] return False
saltstack/salt
salt/roster/sshconfig.py
parse_ssh_config
python
def parse_ssh_config(lines): ''' Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster ''' # transform the list of individual lines into a list of sublists where each # sublist represents a single Host definition hosts = [] for line in lines: line = salt.utils.stringutils.to_unicode(line) if not line or line.startswith('#'): continue elif line.startswith('Host '): hosts.append([]) hosts[-1].append(line) # construct a dictionary of Host names to mapped roster properties targets = collections.OrderedDict() for host_data in hosts: target = collections.OrderedDict() hostnames = host_data[0].split()[1:] for line in host_data[1:]: for field in _ROSTER_FIELDS: match = re.match(field.pattern, line) if match: target[field.target_field] = match.group(1) for hostname in hostnames: targets[hostname] = target # apply matching for glob hosts wildcard_targets = [] non_wildcard_targets = [] for target in targets.keys(): if '*' in target or '?' in target: wildcard_targets.append(target) else: non_wildcard_targets.append(target) for pattern in wildcard_targets: for candidate in non_wildcard_targets: if fnmatch.fnmatch(candidate, pattern): targets[candidate].update(targets[pattern]) del targets[pattern] # finally, update the 'host' to refer to its declaration in the SSH config # so that its connection parameters can be utilized for target in targets: targets[target]['host'] = target return targets
Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L45-L94
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' Parses roster entries out of Host directives from SSH config .. code-block:: bash salt-ssh --roster sshconfig '*' -r "echo hi" ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import collections import fnmatch import re # Import Salt libs import salt.utils.files import salt.utils.stringutils from salt.ext import six import logging log = logging.getLogger(__name__) _SSHConfRegex = collections.namedtuple('_SSHConfRegex', ['target_field', 'pattern']) _ROSTER_FIELDS = ( _SSHConfRegex(target_field='user', pattern=r'\s+User (.*)'), _SSHConfRegex(target_field='port', pattern=r'\s+Port (.*)'), _SSHConfRegex(target_field='priv', pattern=r'\s+IdentityFile (.*)'), ) def _get_ssh_config_file(opts): ''' :return: Path to the .ssh/config file - usually <home>/.ssh/config ''' ssh_config_file = opts.get('ssh_config_file') if not os.path.isfile(ssh_config_file): raise IOError('Cannot find SSH config file') if not os.access(ssh_config_file, os.R_OK): raise IOError('Cannot access SSH config file: {}'.format(ssh_config_file)) return ssh_config_file def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the flat yaml file, checks opts for location but defaults to /etc/salt/roster ''' ssh_config_file = _get_ssh_config_file(__opts__) with salt.utils.files.fopen(ssh_config_file, 'r') as fp: all_minions = parse_ssh_config([line.rstrip() for line in fp]) rmatcher = RosterMatcher(all_minions, tgt, tgt_type) matched = rmatcher.targets() return matched class RosterMatcher(object): ''' Matcher for the roster data structure ''' def __init__(self, raw, tgt, tgt_type): self.tgt = tgt self.tgt_type = tgt_type self.raw = raw def targets(self): ''' Execute the correct tgt_type routine and return ''' try: return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))() except AttributeError: return {} def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions def get_data(self, minion): ''' Return the configured ip ''' if isinstance(self.raw[minion], six.string_types): return {'host': self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] return False
saltstack/salt
salt/roster/sshconfig.py
targets
python
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the flat yaml file, checks opts for location but defaults to /etc/salt/roster ''' ssh_config_file = _get_ssh_config_file(__opts__) with salt.utils.files.fopen(ssh_config_file, 'r') as fp: all_minions = parse_ssh_config([line.rstrip() for line in fp]) rmatcher = RosterMatcher(all_minions, tgt, tgt_type) matched = rmatcher.targets() return matched
Return the targets from the flat yaml file, checks opts for location but defaults to /etc/salt/roster
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L97-L107
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_ssh_config_file(opts):\n '''\n :return: Path to the .ssh/config file - usually <home>/.ssh/config\n '''\n ssh_config_file = opts.get('ssh_config_file')\n if not os.path.isfile(ssh_config_file):\n raise IOError('Cannot find SSH config file')\n if not os.access(ssh_config_file, os.R_OK):\n raise IOError('Cannot access SSH config file: {}'.format(ssh_config_file))\n return ssh_config_file\n", "def parse_ssh_config(lines):\n '''\n Parses lines from the SSH config to create roster targets.\n\n :param lines: Individual lines from the ssh config file\n :return: Dictionary of targets in similar style to the flat roster\n '''\n # transform the list of individual lines into a list of sublists where each\n # sublist represents a single Host definition\n hosts = []\n for line in lines:\n line = salt.utils.stringutils.to_unicode(line)\n if not line or line.startswith('#'):\n continue\n elif line.startswith('Host '):\n hosts.append([])\n hosts[-1].append(line)\n\n # construct a dictionary of Host names to mapped roster properties\n targets = collections.OrderedDict()\n for host_data in hosts:\n target = collections.OrderedDict()\n hostnames = host_data[0].split()[1:]\n for line in host_data[1:]:\n for field in _ROSTER_FIELDS:\n match = re.match(field.pattern, line)\n if match:\n target[field.target_field] = match.group(1)\n for hostname in hostnames:\n targets[hostname] = target\n\n # apply matching for glob hosts\n wildcard_targets = []\n non_wildcard_targets = []\n for target in targets.keys():\n if '*' in target or '?' in target:\n wildcard_targets.append(target)\n else:\n non_wildcard_targets.append(target)\n for pattern in wildcard_targets:\n for candidate in non_wildcard_targets:\n if fnmatch.fnmatch(candidate, pattern):\n targets[candidate].update(targets[pattern])\n del targets[pattern]\n\n # finally, update the 'host' to refer to its declaration in the SSH config\n # so that its connection parameters can be utilized\n for target in targets:\n targets[target]['host'] = target\n return targets\n", "def targets(self):\n '''\n Execute the correct tgt_type routine and return\n '''\n try:\n return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))()\n except AttributeError:\n return {}\n" ]
# -*- coding: utf-8 -*- ''' Parses roster entries out of Host directives from SSH config .. code-block:: bash salt-ssh --roster sshconfig '*' -r "echo hi" ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import collections import fnmatch import re # Import Salt libs import salt.utils.files import salt.utils.stringutils from salt.ext import six import logging log = logging.getLogger(__name__) _SSHConfRegex = collections.namedtuple('_SSHConfRegex', ['target_field', 'pattern']) _ROSTER_FIELDS = ( _SSHConfRegex(target_field='user', pattern=r'\s+User (.*)'), _SSHConfRegex(target_field='port', pattern=r'\s+Port (.*)'), _SSHConfRegex(target_field='priv', pattern=r'\s+IdentityFile (.*)'), ) def _get_ssh_config_file(opts): ''' :return: Path to the .ssh/config file - usually <home>/.ssh/config ''' ssh_config_file = opts.get('ssh_config_file') if not os.path.isfile(ssh_config_file): raise IOError('Cannot find SSH config file') if not os.access(ssh_config_file, os.R_OK): raise IOError('Cannot access SSH config file: {}'.format(ssh_config_file)) return ssh_config_file def parse_ssh_config(lines): ''' Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster ''' # transform the list of individual lines into a list of sublists where each # sublist represents a single Host definition hosts = [] for line in lines: line = salt.utils.stringutils.to_unicode(line) if not line or line.startswith('#'): continue elif line.startswith('Host '): hosts.append([]) hosts[-1].append(line) # construct a dictionary of Host names to mapped roster properties targets = collections.OrderedDict() for host_data in hosts: target = collections.OrderedDict() hostnames = host_data[0].split()[1:] for line in host_data[1:]: for field in _ROSTER_FIELDS: match = re.match(field.pattern, line) if match: target[field.target_field] = match.group(1) for hostname in hostnames: targets[hostname] = target # apply matching for glob hosts wildcard_targets = [] non_wildcard_targets = [] for target in targets.keys(): if '*' in target or '?' in target: wildcard_targets.append(target) else: non_wildcard_targets.append(target) for pattern in wildcard_targets: for candidate in non_wildcard_targets: if fnmatch.fnmatch(candidate, pattern): targets[candidate].update(targets[pattern]) del targets[pattern] # finally, update the 'host' to refer to its declaration in the SSH config # so that its connection parameters can be utilized for target in targets: targets[target]['host'] = target return targets class RosterMatcher(object): ''' Matcher for the roster data structure ''' def __init__(self, raw, tgt, tgt_type): self.tgt = tgt self.tgt_type = tgt_type self.raw = raw def targets(self): ''' Execute the correct tgt_type routine and return ''' try: return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))() except AttributeError: return {} def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions def get_data(self, minion): ''' Return the configured ip ''' if isinstance(self.raw[minion], six.string_types): return {'host': self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] return False
saltstack/salt
salt/roster/sshconfig.py
RosterMatcher.ret_glob_minions
python
def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions
Return minions that match via glob
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L128-L138
null
class RosterMatcher(object): ''' Matcher for the roster data structure ''' def __init__(self, raw, tgt, tgt_type): self.tgt = tgt self.tgt_type = tgt_type self.raw = raw def targets(self): ''' Execute the correct tgt_type routine and return ''' try: return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))() except AttributeError: return {} def get_data(self, minion): ''' Return the configured ip ''' if isinstance(self.raw[minion], six.string_types): return {'host': self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] return False
saltstack/salt
salt/roster/sshconfig.py
RosterMatcher.get_data
python
def get_data(self, minion): ''' Return the configured ip ''' if isinstance(self.raw[minion], six.string_types): return {'host': self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] return False
Return the configured ip
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/sshconfig.py#L140-L148
null
class RosterMatcher(object): ''' Matcher for the roster data structure ''' def __init__(self, raw, tgt, tgt_type): self.tgt = tgt self.tgt_type = tgt_type self.raw = raw def targets(self): ''' Execute the correct tgt_type routine and return ''' try: return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))() except AttributeError: return {} def ret_glob_minions(self): ''' Return minions that match via glob ''' minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions
saltstack/salt
salt/exceptions.py
SaltException.pack
python
def pack(self): ''' Pack this exception into a serializable dictionary that is safe for transport via msgpack ''' if six.PY3: return {'message': six.text_type(self), 'args': self.args} return dict(message=self.__unicode__(), args=self.args)
Pack this exception into a serializable dictionary that is safe for transport via msgpack
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/exceptions.py#L65-L72
[ "def __unicode__(self):\n return self.strerror\n" ]
class SaltException(Exception): ''' Base exception class; all Salt-specific exceptions should subclass this ''' def __init__(self, message=''): # Avoid circular import import salt.utils.stringutils if not isinstance(message, six.string_types): message = six.text_type(message) if six.PY3 or isinstance(message, unicode): # pylint: disable=incompatible-py3-code,undefined-variable super(SaltException, self).__init__( salt.utils.stringutils.to_str(message) ) self.message = self.strerror = message elif isinstance(message, str): super(SaltException, self).__init__(message) self.message = self.strerror = \ salt.utils.stringutils.to_unicode(message) else: # Some non-string input was passed. Run the parent dunder init with # a str version, and convert the passed value to unicode for the # message/strerror attributes. super(SaltException, self).__init__(str(message)) # future lint: blacklisted-function self.message = self.strerror = unicode(message) # pylint: disable=incompatible-py3-code,undefined-variable def __unicode__(self): return self.strerror
saltstack/salt
salt/modules/namecheap_domains.py
reactivate
python
def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult)
Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L54-L80
[ "def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n", "def post_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.post(namecheap_url, data=opts, timeout=45))\n", "def xml_to_dict(xml):\n if xml.nodeType == xml.CDATA_SECTION_NODE:\n return xml.data\n result = atts_to_dict(xml)\n if not [n for n in xml.childNodes if n.nodeType != xml.TEXT_NODE]:\n if result > 0:\n if xml.firstChild is not None and xml.firstChild.data:\n result['data'] = xml.firstChild.data\n elif xml.firstChild is not None and xml.firstChild.data:\n return xml.firstChild.data\n else:\n return None\n elif xml.childNodes.length == 1 and \\\n xml.childNodes[0].nodeType == xml.CDATA_SECTION_NODE:\n return xml.childNodes[0].data\n else:\n for n in xml.childNodes:\n if n.nodeType == xml.CDATA_SECTION_NODE:\n\n if xml.tagName.lower() in result:\n val = result[xml.tagName.lower()]\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(n.data)\n result[xml.tagName.lower()] = val\n else:\n result[xml.tagName.lower()] = n.data\n\n elif n.nodeType != xml.TEXT_NODE:\n\n if n.tagName.lower() in result:\n val = result[n.tagName.lower()]\n\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(xml_to_dict(n))\n result[n.tagName.lower()] = val\n else:\n result[n.tagName.lower()] = xml_to_dict(n)\n return result\n" ]
# -*- coding: utf-8 -*- ''' Namecheap Domain Management .. versionadded:: 2017.7.0 Prerequisites ------------- This module uses the ``requests`` Python module to communicate to the namecheap API. Configuration ------------- The Namecheap username, API key and URL should be set in the minion configuration file, or in the Pillar data. .. code-block:: yaml namecheap.name: companyname namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3 namecheap.client_ip: 162.155.30.172 #Real url namecheap.url: https://api.namecheap.com/xml.response #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response ''' from __future__ import absolute_import, print_function, unicode_literals import logging CAN_USE_NAMECHEAP = True try: import salt.utils.namecheap except ImportError: CAN_USE_NAMECHEAP = False # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Check to make sure requests and xml are installed and requests ''' if CAN_USE_NAMECHEAP: return 'namecheap_domains' return False def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult) def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult) def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult) def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
saltstack/salt
salt/modules/namecheap_domains.py
renew
python
def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult)
Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L83-L120
[ "def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n", "def post_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.post(namecheap_url, data=opts, timeout=45))\n", "def xml_to_dict(xml):\n if xml.nodeType == xml.CDATA_SECTION_NODE:\n return xml.data\n result = atts_to_dict(xml)\n if not [n for n in xml.childNodes if n.nodeType != xml.TEXT_NODE]:\n if result > 0:\n if xml.firstChild is not None and xml.firstChild.data:\n result['data'] = xml.firstChild.data\n elif xml.firstChild is not None and xml.firstChild.data:\n return xml.firstChild.data\n else:\n return None\n elif xml.childNodes.length == 1 and \\\n xml.childNodes[0].nodeType == xml.CDATA_SECTION_NODE:\n return xml.childNodes[0].data\n else:\n for n in xml.childNodes:\n if n.nodeType == xml.CDATA_SECTION_NODE:\n\n if xml.tagName.lower() in result:\n val = result[xml.tagName.lower()]\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(n.data)\n result[xml.tagName.lower()] = val\n else:\n result[xml.tagName.lower()] = n.data\n\n elif n.nodeType != xml.TEXT_NODE:\n\n if n.tagName.lower() in result:\n val = result[n.tagName.lower()]\n\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(xml_to_dict(n))\n result[n.tagName.lower()] = val\n else:\n result[n.tagName.lower()] = xml_to_dict(n)\n return result\n" ]
# -*- coding: utf-8 -*- ''' Namecheap Domain Management .. versionadded:: 2017.7.0 Prerequisites ------------- This module uses the ``requests`` Python module to communicate to the namecheap API. Configuration ------------- The Namecheap username, API key and URL should be set in the minion configuration file, or in the Pillar data. .. code-block:: yaml namecheap.name: companyname namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3 namecheap.client_ip: 162.155.30.172 #Real url namecheap.url: https://api.namecheap.com/xml.response #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response ''' from __future__ import absolute_import, print_function, unicode_literals import logging CAN_USE_NAMECHEAP = True try: import salt.utils.namecheap except ImportError: CAN_USE_NAMECHEAP = False # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Check to make sure requests and xml are installed and requests ''' if CAN_USE_NAMECHEAP: return 'namecheap_domains' return False def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult) def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult) def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult) def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
saltstack/salt
salt/modules/namecheap_domains.py
create
python
def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult)
Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L123-L209
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n", "def post_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.post(namecheap_url, data=opts, timeout=45))\n", "def atts_to_dict(xml):\n result = {}\n if xml.attributes is not None:\n for key, value in xml.attributes.items():\n result[key.lower()] = string_to_value(value)\n return result\n", "def add_to_opts(opts_dict, kwargs, value, suffix, prefices):\n for prefix in prefices:\n nextkey = prefix + suffix\n if nextkey not in kwargs:\n opts_dict[nextkey] = value\n" ]
# -*- coding: utf-8 -*- ''' Namecheap Domain Management .. versionadded:: 2017.7.0 Prerequisites ------------- This module uses the ``requests`` Python module to communicate to the namecheap API. Configuration ------------- The Namecheap username, API key and URL should be set in the minion configuration file, or in the Pillar data. .. code-block:: yaml namecheap.name: companyname namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3 namecheap.client_ip: 162.155.30.172 #Real url namecheap.url: https://api.namecheap.com/xml.response #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response ''' from __future__ import absolute_import, print_function, unicode_literals import logging CAN_USE_NAMECHEAP = True try: import salt.utils.namecheap except ImportError: CAN_USE_NAMECHEAP = False # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Check to make sure requests and xml are installed and requests ''' if CAN_USE_NAMECHEAP: return 'namecheap_domains' return False def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult) def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult) def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult) def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
saltstack/salt
salt/modules/namecheap_domains.py
check
python
def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked
Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L212-L241
[ "def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n", "def get_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.get(namecheap_url, params=opts, timeout=45))\n", "def string_to_value(value):\n temp = value.lower()\n result = None\n if temp == \"true\":\n result = True\n elif temp == \"false\":\n result = False\n else:\n try:\n result = int(value)\n except ValueError:\n try:\n result = float(value)\n except ValueError:\n result = value\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' Namecheap Domain Management .. versionadded:: 2017.7.0 Prerequisites ------------- This module uses the ``requests`` Python module to communicate to the namecheap API. Configuration ------------- The Namecheap username, API key and URL should be set in the minion configuration file, or in the Pillar data. .. code-block:: yaml namecheap.name: companyname namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3 namecheap.client_ip: 162.155.30.172 #Real url namecheap.url: https://api.namecheap.com/xml.response #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response ''' from __future__ import absolute_import, print_function, unicode_literals import logging CAN_USE_NAMECHEAP = True try: import salt.utils.namecheap except ImportError: CAN_USE_NAMECHEAP = False # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Check to make sure requests and xml are installed and requests ''' if CAN_USE_NAMECHEAP: return 'namecheap_domains' return False def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult) def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult) def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult) def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult) def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
saltstack/salt
salt/modules/namecheap_domains.py
get_info
python
def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult)
Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L244-L269
[ "def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n", "def get_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.get(namecheap_url, params=opts, timeout=45))\n", "def xml_to_dict(xml):\n if xml.nodeType == xml.CDATA_SECTION_NODE:\n return xml.data\n result = atts_to_dict(xml)\n if not [n for n in xml.childNodes if n.nodeType != xml.TEXT_NODE]:\n if result > 0:\n if xml.firstChild is not None and xml.firstChild.data:\n result['data'] = xml.firstChild.data\n elif xml.firstChild is not None and xml.firstChild.data:\n return xml.firstChild.data\n else:\n return None\n elif xml.childNodes.length == 1 and \\\n xml.childNodes[0].nodeType == xml.CDATA_SECTION_NODE:\n return xml.childNodes[0].data\n else:\n for n in xml.childNodes:\n if n.nodeType == xml.CDATA_SECTION_NODE:\n\n if xml.tagName.lower() in result:\n val = result[xml.tagName.lower()]\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(n.data)\n result[xml.tagName.lower()] = val\n else:\n result[xml.tagName.lower()] = n.data\n\n elif n.nodeType != xml.TEXT_NODE:\n\n if n.tagName.lower() in result:\n val = result[n.tagName.lower()]\n\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(xml_to_dict(n))\n result[n.tagName.lower()] = val\n else:\n result[n.tagName.lower()] = xml_to_dict(n)\n return result\n" ]
# -*- coding: utf-8 -*- ''' Namecheap Domain Management .. versionadded:: 2017.7.0 Prerequisites ------------- This module uses the ``requests`` Python module to communicate to the namecheap API. Configuration ------------- The Namecheap username, API key and URL should be set in the minion configuration file, or in the Pillar data. .. code-block:: yaml namecheap.name: companyname namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3 namecheap.client_ip: 162.155.30.172 #Real url namecheap.url: https://api.namecheap.com/xml.response #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response ''' from __future__ import absolute_import, print_function, unicode_literals import logging CAN_USE_NAMECHEAP = True try: import salt.utils.namecheap except ImportError: CAN_USE_NAMECHEAP = False # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Check to make sure requests and xml are installed and requests ''' if CAN_USE_NAMECHEAP: return 'namecheap_domains' return False def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult) def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult) def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult) def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
saltstack/salt
salt/modules/namecheap_domains.py
get_tld_list
python
def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds
Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L272-L301
[ "def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n", "def get_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.get(namecheap_url, params=opts, timeout=45))\n", "def atts_to_dict(xml):\n result = {}\n if xml.attributes is not None:\n for key, value in xml.attributes.items():\n result[key.lower()] = string_to_value(value)\n return result\n" ]
# -*- coding: utf-8 -*- ''' Namecheap Domain Management .. versionadded:: 2017.7.0 Prerequisites ------------- This module uses the ``requests`` Python module to communicate to the namecheap API. Configuration ------------- The Namecheap username, API key and URL should be set in the minion configuration file, or in the Pillar data. .. code-block:: yaml namecheap.name: companyname namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3 namecheap.client_ip: 162.155.30.172 #Real url namecheap.url: https://api.namecheap.com/xml.response #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response ''' from __future__ import absolute_import, print_function, unicode_literals import logging CAN_USE_NAMECHEAP = True try: import salt.utils.namecheap except ImportError: CAN_USE_NAMECHEAP = False # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Check to make sure requests and xml are installed and requests ''' if CAN_USE_NAMECHEAP: return 'namecheap_domains' return False def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult) def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult) def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult) def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult) def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
saltstack/salt
salt/modules/namecheap_domains.py
get_list
python
def get_list(list_type=None, search_term=None, page=None, page_size=None, sort_by=None): ''' Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getList') if list_type is not None: if list_type not in ['ALL', 'EXPIRING', 'EXPIRED']: log.error('Invalid option for list_type') raise Exception('Invalid option for list_type') opts['ListType'] = list_type if search_term is not None: if len(search_term) > 70: log.warning('search_term trimmed to first 70 characters') search_term = search_term[0:70] opts['SearchTerm'] = search_term if page is not None: opts['Page'] = page if page_size is not None: if page_size > 100 or page_size < 10: log.error('Invalid option for page') raise Exception('Invalid option for page') opts['PageSize'] = page_size if sort_by is not None: if sort_by not in ['NAME', 'NAME_DESC', 'EXPIREDATE', 'EXPIREDATE_DESC', 'CREATEDATE', 'CREATEDATE_DESC']: log.error('Invalid option for sort_by') raise Exception('Invalid option for sort_by') opts['SortBy'] = sort_by response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domainresult = response_xml.getElementsByTagName("DomainGetListResult")[0] domains = [] for d in domainresult.getElementsByTagName("Domain"): domains.append(salt.utils.namecheap.atts_to_dict(d)) return domains
Returns a list of domains for the particular user as a list of objects offset by ``page`` length of ``page_size`` list_type : ALL One of ``ALL``, ``EXPIRING``, ``EXPIRED`` search_term Keyword to look for on the domain list page : 1 Number of result page to return page_size : 20 Number of domains to be listed per page (minimum: ``10``, maximum: ``100``) sort_by One of ``NAME``, ``NAME_DESC``, ``EXPIREDATE``, ``EXPIREDATE_DESC``, ``CREATEDATE``, or ``CREATEDATE_DESC`` CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains.py#L304-L376
[ "def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n", "def get_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.get(namecheap_url, params=opts, timeout=45))\n", "def atts_to_dict(xml):\n result = {}\n if xml.attributes is not None:\n for key, value in xml.attributes.items():\n result[key.lower()] = string_to_value(value)\n return result\n" ]
# -*- coding: utf-8 -*- ''' Namecheap Domain Management .. versionadded:: 2017.7.0 Prerequisites ------------- This module uses the ``requests`` Python module to communicate to the namecheap API. Configuration ------------- The Namecheap username, API key and URL should be set in the minion configuration file, or in the Pillar data. .. code-block:: yaml namecheap.name: companyname namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3 namecheap.client_ip: 162.155.30.172 #Real url namecheap.url: https://api.namecheap.com/xml.response #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response ''' from __future__ import absolute_import, print_function, unicode_literals import logging CAN_USE_NAMECHEAP = True try: import salt.utils.namecheap except ImportError: CAN_USE_NAMECHEAP = False # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Check to make sure requests and xml are installed and requests ''' if CAN_USE_NAMECHEAP: return 'namecheap_domains' return False def reactivate(domain_name): ''' Try to reactivate the expired domain name Returns the following information: - Whether or not the domain was reactivated successfully - The amount charged for reactivation - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.reactivate my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.reactivate') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainreactivateresult = response_xml.getElementsByTagName('DomainReactivateResult')[0] return salt.utils.namecheap.xml_to_dict(domainreactivateresult) def renew(domain_name, years, promotion_code=None): ''' Try to renew the specified expiring domain name for a specified number of years domain_name The domain name to be renewed years Number of years to renew Returns the following information: - Whether or not the domain was renewed successfully - The domain ID - The order ID - The transaction ID - The amount charged for renewal CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.renew my-domain-name 5 ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.renew') opts['DomainName'] = domain_name opts['Years'] = years if promotion_code is not None: opts['PromotionCode'] = promotion_code response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainrenewresult = response_xml.getElementsByTagName("DomainRenewResult")[0] return salt.utils.namecheap.xml_to_dict(domainrenewresult) def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not WhoisGuard is enabled - Whether or not registration is instant - The amount charged for registration - The domain ID - The order ID - The transaction ID CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.create my-domain-name 2 ''' idn_codes = ('afr', 'alb', 'ara', 'arg', 'arm', 'asm', 'ast', 'ave', 'awa', 'aze', 'bak', 'bal', 'ban', 'baq', 'bas', 'bel', 'ben', 'bho', 'bos', 'bul', 'bur', 'car', 'cat', 'che', 'chi', 'chv', 'cop', 'cos', 'cze', 'dan', 'div', 'doi', 'dut', 'eng', 'est', 'fao', 'fij', 'fin', 'fre', 'fry', 'geo', 'ger', 'gla', 'gle', 'gon', 'gre', 'guj', 'heb', 'hin', 'hun', 'inc', 'ind', 'inh', 'isl', 'ita', 'jav', 'jpn', 'kas', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mkd', 'mlt', 'mol', 'mon', 'mri', 'msa', 'nep', 'nor', 'ori', 'oss', 'pan', 'per', 'pol', 'por', 'pus', 'raj', 'rum', 'rus', 'san', 'scr', 'sin', 'slo', 'slv', 'smo', 'snd', 'som', 'spa', 'srd', 'srp', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tha', 'tib', 'tur', 'ukr', 'urd', 'uzb', 'vie', 'wel', 'yid') require_opts = ['AdminAddress1', 'AdminCity', 'AdminCountry', 'AdminEmailAddress', 'AdminFirstName', 'AdminLastName', 'AdminPhone', 'AdminPostalCode', 'AdminStateProvince', 'AuxBillingAddress1', 'AuxBillingCity', 'AuxBillingCountry', 'AuxBillingEmailAddress', 'AuxBillingFirstName', 'AuxBillingLastName', 'AuxBillingPhone', 'AuxBillingPostalCode', 'AuxBillingStateProvince', 'RegistrantAddress1', 'RegistrantCity', 'RegistrantCountry', 'RegistrantEmailAddress', 'RegistrantFirstName', 'RegistrantLastName', 'RegistrantPhone', 'RegistrantPostalCode', 'RegistrantStateProvince', 'TechAddress1', 'TechCity', 'TechCountry', 'TechEmailAddress', 'TechFirstName', 'TechLastName', 'TechPhone', 'TechPostalCode', 'TechStateProvince', 'Years'] opts = salt.utils.namecheap.get_opts('namecheap.domains.create') opts['DomainName'] = domain_name opts['Years'] = six.text_type(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: nextkey = prefix + suffix if nextkey not in kwargs: opts_dict[nextkey] = value for key, value in six.iteritems(kwargs): if key.startswith('Registrant'): add_to_opts(opts, kwargs, value, key[10:], ['Tech', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Tech'): add_to_opts(opts, kwargs, value, key[4:], ['Registrant', 'Admin', 'AuxBilling', 'Billing']) if key.startswith('Admin'): add_to_opts(opts, kwargs, value, key[5:], ['Registrant', 'Tech', 'AuxBilling', 'Billing']) if key.startswith('AuxBilling'): add_to_opts(opts, kwargs, value, key[10:], ['Registrant', 'Tech', 'Admin', 'Billing']) if key.startswith('Billing'): add_to_opts(opts, kwargs, value, key[7:], ['Registrant', 'Tech', 'Admin', 'AuxBilling']) if key == 'IdnCode' and key not in idn_codes: log.error('Invalid IdnCode') raise Exception('Invalid IdnCode') opts[key] = value for requiredkey in require_opts: if requiredkey not in opts: log.error('Missing required parameter \'%s\'', requiredkey) raise Exception('Missing required parameter \'{0}\''.format(requiredkey)) response_xml = salt.utils.namecheap.post_request(opts) if response_xml is None: return {} domainresult = response_xml.getElementsByTagName("DomainCreateResult")[0] return salt.utils.namecheap.atts_to_dict(domainresult) def check(*domains_to_check): ''' Checks the availability of domains domains_to_check array of strings List of domains to check Returns a dictionary mapping the each domain name to a boolean denoting whether or not it is available. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.check domain-to-check ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.check') opts['DomainList'] = ','.join(domains_to_check) response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") domains_checked[result.getAttribute("Domain").lower()] = salt.utils.namecheap.string_to_value(available) return domains_checked def get_info(domain_name): ''' Returns information about the requested domain returns a dictionary of information about the domain_name domain_name string Domain name to get information about CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_info my-domain-name ''' opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo') opts['DomainName'] = domain_name response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return [] domaingetinforesult = response_xml.getElementsByTagName("DomainGetInfoResult")[0] return salt.utils.namecheap.xml_to_dict(domaingetinforesult) def get_tld_list(): ''' Returns a list of TLDs as objects CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains.get_tld_list ''' response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist')) if response_xml is None: return [] tldresult = response_xml.getElementsByTagName("Tlds")[0] tlds = [] for e in tldresult.getElementsByTagName("Tld"): tld = salt.utils.namecheap.atts_to_dict(e) tld['data'] = e.firstChild.data categories = [] subcategories = e.getElementsByTagName("Categories")[0] for c in subcategories.getElementsByTagName("TldCategory"): categories.append(salt.utils.namecheap.atts_to_dict(c)) tld['categories'] = categories tlds.append(tld) return tlds
saltstack/salt
salt/pillar/reclass_adapter.py
ext_pillar
python
def ext_pillar(minion_id, pillar, **kwargs): ''' Obtain the Pillar data from **reclass** for the given ``minion_id``. ''' # If reclass is installed, __virtual__ put it onto the search path, so we # don't need to protect against ImportError: # pylint: disable=3rd-party-module-not-gated from reclass.adapters.salt import ext_pillar as reclass_ext_pillar from reclass.errors import ReclassException # pylint: enable=3rd-party-module-not-gated try: # the source path we used above isn't something reclass needs to care # about, so filter it: filter_out_source_path_option(kwargs) # if no inventory_base_uri was specified, initialize it to the first # file_roots of class 'base' (if that exists): set_inventory_base_uri_default(__opts__, kwargs) # I purposely do not pass any of __opts__ or __salt__ or __grains__ # to reclass, as I consider those to be Salt-internal and reclass # should not make any assumptions about it. return reclass_ext_pillar(minion_id, pillar, **kwargs) except TypeError as e: if 'unexpected keyword argument' in six.text_type(e): arg = six.text_type(e).split()[-1] raise SaltInvocationError('ext_pillar.reclass: unexpected option: ' + arg) else: raise except KeyError as e: if 'id' in six.text_type(e): raise SaltInvocationError('ext_pillar.reclass: __opts__ does not ' 'define minion ID') else: raise except ReclassException as e: raise SaltInvocationError('ext_pillar.reclass: {0}'.format(e))
Obtain the Pillar data from **reclass** for the given ``minion_id``.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/reclass_adapter.py#L93-L135
[ "def filter_out_source_path_option(opts):\n if 'reclass_source_path' in opts:\n del opts['reclass_source_path']\n", "def set_inventory_base_uri_default(config, opts):\n if 'inventory_base_uri' in opts:\n return\n\n base_roots = config.get('file_roots', {}).get('base', [])\n if base_roots:\n opts['inventory_base_uri'] = base_roots[0]\n" ]
# -*- coding: utf-8 -*- ''' Use the "reclass" database as a Pillar source .. |reclass| replace:: **reclass** This ``ext_pillar`` plugin provides access to the |reclass| database, such that Pillar data for a specific minion are fetched using |reclass|. You can find more information about |reclass| at http://reclass.pantsfullofunix.net. To use the plugin, add it to the ``ext_pillar`` list in the Salt master config and tell |reclass| by way of a few options how and where to find the inventory: .. code-block:: yaml ext_pillar: - reclass: storage_type: yaml_fs inventory_base_uri: /srv/salt This would cause |reclass| to read the inventory from YAML files in ``/srv/salt/nodes`` and ``/srv/salt/classes``. If you are also using |reclass| as ``master_tops`` plugin, and you want to avoid having to specify the same information for both, use YAML anchors (take note of the differing data types for ``ext_pillar`` and ``master_tops``): .. code-block:: yaml reclass: &reclass storage_type: yaml_fs inventory_base_uri: /srv/salt reclass_source_path: ~/code/reclass ext_pillar: - reclass: *reclass master_tops: reclass: *reclass If you want to run reclass from source, rather than installing it, you can either let the master know via the ``PYTHONPATH`` environment variable, or by setting the configuration option, like in the example above. ''' # This file cannot be called reclass.py, because then the module import would # not work. Thanks to the __virtual__ function, however, the plugin still # responds to the name 'reclass'. # Import python libs from __future__ import absolute_import, print_function, unicode_literals # Import salt libs from salt.exceptions import SaltInvocationError from salt.utils.reclass import ( prepend_reclass_source_path, filter_out_source_path_option, set_inventory_base_uri_default ) # Import 3rd-party libs from salt.ext import six # Define the module's virtual name __virtualname__ = 'reclass' def __virtual__(retry=False): try: import reclass # pylint: disable=unused-import return __virtualname__ except ImportError as e: if retry: return False for pillar in __opts__.get('ext_pillar', []): if 'reclass' not in pillar: continue # each pillar entry is a single-key hash of name -> options opts = next(six.itervalues(pillar)) prepend_reclass_source_path(opts) break return __virtual__(retry=True)
saltstack/salt
salt/modules/zcbuildout.py
_set_status
python
def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m)
Assign status data to a dict.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L209-L248
[ "def _encode_string(string):\n if isinstance(string, six.text_type):\n string = string.encode('utf-8')\n return string\n", "def _encode_status(status):\n status['out'] = _encode_string(status['out'])\n status['outlog_by_level'] = _encode_string(status['outlog_by_level'])\n if status['logs']:\n for i, data in enumerate(status['logs'][:]):\n status['logs'][i] = (data[0], _encode_string(data[1]))\n for logger in 'error', 'warn', 'info', 'debug':\n logs = status['logs_by_level'].get(logger, [])[:]\n if logs:\n for i, log in enumerate(logs):\n status['logs_by_level'][logger][i] = _encode_string(log)\n return status\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
_invalid
python
def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out)
Return invalid status.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L251-L255
null
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
_valid
python
def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out)
Return valid status.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L258-L262
null
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
_Popen
python
def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret
Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L265-L312
[ "def debug(self, msg):\n self._log('debug', msg)\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
_find_cfgs
python
def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs
Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L353-L388
[ "def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
_get_bootstrap_content
python
def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent
Get the current bootstrap.py script content
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L391-L404
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
_get_buildout_ver
python
def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver
Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L407-L441
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _get_bootstrap_content(directory='.'):\n '''\n Get the current bootstrap.py script content\n '''\n try:\n with salt.utils.files.fopen(os.path.join(\n os.path.abspath(directory),\n 'bootstrap.py')) as fic:\n oldcontent = salt.utils.stringutils.to_unicode(\n fic.read()\n )\n except (OSError, IOError):\n oldcontent = ''\n return oldcontent\n", "def _find_cfgs(path, cfgs=None):\n '''\n Find all buildout configs in a subdirectory.\n only buildout.cfg and etc/buildout.cfg are valid in::\n\n path\n directory where to start to search\n\n cfg\n a optional list to append to\n\n .\n ├── buildout.cfg\n ├── etc\n │   └── buildout.cfg\n ├── foo\n │   └── buildout.cfg\n └── var\n └── buildout.cfg\n '''\n ignored = ['var', 'parts']\n dirs = []\n if not cfgs:\n cfgs = []\n for i in os.listdir(path):\n fi = os.path.join(path, i)\n if fi.endswith('.cfg') and os.path.isfile(fi):\n cfgs.append(fi)\n if os.path.isdir(fi) and (i not in ignored):\n dirs.append(fi)\n for fpath in dirs:\n for p, ids, ifs in salt.utils.path.os_walk(fpath):\n for i in ifs:\n if i.endswith('.cfg'):\n cfgs.append(os.path.join(p, i))\n return cfgs\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
_get_bootstrap_url
python
def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER])
Get the most appropriate download URL for the bootstrap script. directory directory to execute in
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L444-L453
[ "def _get_buildout_ver(directory='.'):\n '''Check for buildout versions.\n\n In any cases, check for a version pinning\n Also check for buildout.dumppickedversions which is buildout1 specific\n Also check for the version targeted by the local bootstrap file\n Take as default buildout2\n\n directory\n directory to execute in\n '''\n directory = os.path.abspath(directory)\n buildoutver = 2\n try:\n files = _find_cfgs(directory)\n for f in files:\n with salt.utils.files.fopen(f) as fic:\n buildout1re = re.compile(r'^zc\\.buildout\\s*=\\s*1', RE_F)\n dfic = salt.utils.stringutils.to_unicode(fic.read())\n if (\n ('buildout.dumppick' in dfic)\n or\n (buildout1re.search(dfic))\n ):\n buildoutver = 1\n bcontent = _get_bootstrap_content(directory)\n if (\n '--download-base' in bcontent\n or '--setup-source' in bcontent\n or '--distribute' in bcontent\n ):\n buildoutver = 1\n except (OSError, IOError):\n pass\n return buildoutver\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
upgrade_bootstrap
python
def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment}
Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L468-L553
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n", "def _get_bootstrap_url(directory):\n '''\n Get the most appropriate download URL for the bootstrap script.\n\n directory\n directory to execute in\n\n '''\n v = _get_buildout_ver(directory)\n return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER])\n", "def _get_buildout_ver(directory='.'):\n '''Check for buildout versions.\n\n In any cases, check for a version pinning\n Also check for buildout.dumppickedversions which is buildout1 specific\n Also check for the version targeted by the local bootstrap file\n Take as default buildout2\n\n directory\n directory to execute in\n '''\n directory = os.path.abspath(directory)\n buildoutver = 2\n try:\n files = _find_cfgs(directory)\n for f in files:\n with salt.utils.files.fopen(f) as fic:\n buildout1re = re.compile(r'^zc\\.buildout\\s*=\\s*1', RE_F)\n dfic = salt.utils.stringutils.to_unicode(fic.read())\n if (\n ('buildout.dumppick' in dfic)\n or\n (buildout1re.search(dfic))\n ):\n buildoutver = 1\n bcontent = _get_bootstrap_content(directory)\n if (\n '--download-base' in bcontent\n or '--setup-source' in bcontent\n or '--distribute' in bcontent\n ):\n buildoutver = 1\n except (OSError, IOError):\n pass\n return buildoutver\n", "def _get_bootstrap_content(directory='.'):\n '''\n Get the current bootstrap.py script content\n '''\n try:\n with salt.utils.files.fopen(os.path.join(\n os.path.abspath(directory),\n 'bootstrap.py')) as fic:\n oldcontent = salt.utils.stringutils.to_unicode(\n fic.read()\n )\n except (OSError, IOError):\n oldcontent = ''\n return oldcontent\n", "def _dot_buildout(directory):\n '''\n Get the local marker directory.\n\n directory\n directory to execute in\n '''\n return os.path.join(\n os.path.abspath(directory), '.buildout')\n", "def debug(self, msg):\n self._log('debug', msg)\n", "def info(self, msg):\n self._log('info', msg)\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
bootstrap
python
def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output}
Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L557-L764
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _Popen(command,\n output=False,\n directory='.',\n runas=None,\n env=(),\n exitcode=0,\n use_vt=False,\n loglevel=None):\n '''\n Run a command.\n\n output\n return output if true\n\n directory\n directory to execute in\n\n runas\n user used to run buildout as\n\n env\n environment variables to set when running\n\n exitcode\n fails if cmd does not return this exit code\n (set to None to disable check)\n\n use_vt\n Use the new salt VT to stream output [experimental]\n\n '''\n ret = None\n directory = os.path.abspath(directory)\n if isinstance(command, list):\n command = ' '.join(command)\n LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging\n if not loglevel:\n loglevel = 'debug'\n ret = __salt__['cmd.run_all'](\n command, cwd=directory, output_loglevel=loglevel,\n runas=runas, env=env, use_vt=use_vt, python_shell=False)\n out = ret['stdout'] + '\\n\\n' + ret['stderr']\n if (exitcode is not None) and (ret['retcode'] != exitcode):\n raise _BuildoutError(out)\n ret['output'] = out\n if output:\n ret = out\n return ret\n", "def _has_old_distribute(python=sys.executable, runas=None, env=()):\n old_distribute = False\n try:\n cmd = [python,\n '-c',\n '\\'import pkg_resources;'\n 'print pkg_resources.'\n 'get_distribution(\\\"distribute\\\").location\\'']\n ret = _Popen(cmd, runas=runas, env=env, output=True)\n if 'distribute-0.6' in ret:\n old_distribute = True\n except Exception:\n old_distribute = False\n return old_distribute\n", "def _has_setuptools7(python=sys.executable, runas=None, env=()):\n new_st = False\n try:\n cmd = [python,\n '-c',\n '\\'import pkg_resources;'\n 'print not pkg_resources.'\n 'get_distribution(\"setuptools\").version.startswith(\"0.6\")\\'']\n ret = _Popen(cmd, runas=runas, env=env, output=True)\n if 'true' in ret.lower():\n new_st = True\n except Exception:\n new_st = False\n return new_st\n", "def _dot_buildout(directory):\n '''\n Get the local marker directory.\n\n directory\n directory to execute in\n '''\n return os.path.join(\n os.path.abspath(directory), '.buildout')\n", "def _call_callback(*a, **kw):\n # cleanup the module kwargs before calling it from the\n # decorator\n kw = copy.deepcopy(kw)\n for k in [ar for ar in kw if '__pub' in ar]:\n kw.pop(k, None)\n st = BASE_STATUS.copy()\n directory = kw.get('directory', '.')\n onlyif = kw.get('onlyif', None)\n unless = kw.get('unless', None)\n runas = kw.get('runas', None)\n env = kw.get('env', ())\n status = BASE_STATUS.copy()\n try:\n # may rise _ResultTransmission\n status = _check_onlyif_unless(onlyif,\n unless,\n directory=directory,\n runas=runas,\n env=env)\n # if onlyif/unless returns, we are done\n if status is None:\n status = BASE_STATUS.copy()\n comment, st = '', True\n out = func(*a, **kw)\n # we may have already final statuses not to be touched\n # merged_statuses flag is there to check that !\n if not isinstance(out, dict):\n status = _valid(status, out=out)\n else:\n if out.get('merged_statuses', False):\n status = out\n else:\n status = _set_status(status,\n status=out.get('status', True),\n comment=out.get('comment', ''),\n out=out.get('out', out))\n except Exception:\n trace = traceback.format_exc(None)\n LOG.error(trace)\n _invalid(status)\n LOG.clear()\n # before returning, trying to compact the log output\n for k in ['comment', 'out', 'outlog']:\n if status[k] and isinstance(status[k], six.string_types):\n status[k] = '\\n'.join([\n log\n for log in status[k].split('\\n')\n if log.strip()])\n return status\n", "def warn(self, msg):\n self._log('warn', msg)\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
run_buildout
python
def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)}
Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L768-L870
[ "def _Popen(command,\n output=False,\n directory='.',\n runas=None,\n env=(),\n exitcode=0,\n use_vt=False,\n loglevel=None):\n '''\n Run a command.\n\n output\n return output if true\n\n directory\n directory to execute in\n\n runas\n user used to run buildout as\n\n env\n environment variables to set when running\n\n exitcode\n fails if cmd does not return this exit code\n (set to None to disable check)\n\n use_vt\n Use the new salt VT to stream output [experimental]\n\n '''\n ret = None\n directory = os.path.abspath(directory)\n if isinstance(command, list):\n command = ' '.join(command)\n LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging\n if not loglevel:\n loglevel = 'debug'\n ret = __salt__['cmd.run_all'](\n command, cwd=directory, output_loglevel=loglevel,\n runas=runas, env=env, use_vt=use_vt, python_shell=False)\n out = ret['stdout'] + '\\n\\n' + ret['stderr']\n if (exitcode is not None) and (ret['retcode'] != exitcode):\n raise _BuildoutError(out)\n ret['output'] = out\n if output:\n ret = out\n return ret\n", "def debug(self, msg):\n self._log('debug', msg)\n", "def info(self, msg):\n self._log('info', msg)\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret]) def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/modules/zcbuildout.py
buildout
python
def buildout(directory='.', config='buildout.cfg', parts=None, runas=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, newest=False, python=sys.executable, debug=False, verbose=False, onlyif=None, unless=None, use_vt=False, loglevel=None): ''' Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout ''' LOG.info('Running buildout in {0} ({1})'.format(directory, config)) # pylint: disable=str-format-in-logging boot_ret = bootstrap(directory, config=config, buildout_ver=buildout_ver, test_release=test_release, offline=offline, new_st=new_st, env=env, runas=runas, distribute=distribute, python=python, use_vt=use_vt, loglevel=loglevel) buildout_ret = run_buildout(directory=directory, config=config, parts=parts, offline=offline, newest=newest, runas=runas, env=env, verbose=verbose, debug=debug, use_vt=use_vt, loglevel=loglevel) # signal the decorator or our return return _merge_statuses([boot_ret, buildout_ret])
Run buildout in a directory. directory directory to execute in config buildout config to use parts specific buildout parts to run runas user used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release new_st Forcing use of setuptools >= 0.7 distribute use distribute over setuptools if possible offline does buildout run offline python python to use debug run buildout with -D debug flag onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.buildout /srv/mybuildout
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zcbuildout.py#L922-L1024
[ "def _merge_statuses(statuses):\n status = BASE_STATUS.copy()\n status['status'] = None\n status['merged_statuses'] = True\n status['out'] = []\n for st in statuses:\n if status['status'] is not False:\n status['status'] = st['status']\n out = st['out']\n comment = _encode_string(st['comment'])\n logs = st['logs']\n logs_by_level = st['logs_by_level']\n outlog_by_level = st['outlog_by_level']\n outlog = st['outlog']\n if out:\n if not status['out']:\n status['out'] = ''\n status['out'] += '\\n'\n status['out'] += HR\n out = _encode_string(out)\n status['out'] += '{0}\\n'.format(out)\n status['out'] += HR\n if comment:\n if not status['comment']:\n status['comment'] = ''\n status['comment'] += '\\n{0}\\n'.format(\n _encode_string(comment))\n if outlog:\n if not status['outlog']:\n status['outlog'] = ''\n outlog = _encode_string(outlog)\n status['outlog'] += '\\n{0}'.format(HR)\n status['outlog'] += outlog\n if outlog_by_level:\n if not status['outlog_by_level']:\n status['outlog_by_level'] = ''\n status['outlog_by_level'] += '\\n{0}'.format(HR)\n status['outlog_by_level'] += _encode_string(outlog_by_level)\n status['logs'].extend([\n (a[0], _encode_string(a[1])) for a in logs])\n for log in logs_by_level:\n if log not in status['logs_by_level']:\n status['logs_by_level'][log] = []\n status['logs_by_level'][log].extend(\n [_encode_string(a) for a in logs_by_level[log]])\n return _encode_status(status)\n", "def _call_callback(*a, **kw):\n # cleanup the module kwargs before calling it from the\n # decorator\n kw = copy.deepcopy(kw)\n for k in [ar for ar in kw if '__pub' in ar]:\n kw.pop(k, None)\n st = BASE_STATUS.copy()\n directory = kw.get('directory', '.')\n onlyif = kw.get('onlyif', None)\n unless = kw.get('unless', None)\n runas = kw.get('runas', None)\n env = kw.get('env', ())\n status = BASE_STATUS.copy()\n try:\n # may rise _ResultTransmission\n status = _check_onlyif_unless(onlyif,\n unless,\n directory=directory,\n runas=runas,\n env=env)\n # if onlyif/unless returns, we are done\n if status is None:\n status = BASE_STATUS.copy()\n comment, st = '', True\n out = func(*a, **kw)\n # we may have already final statuses not to be touched\n # merged_statuses flag is there to check that !\n if not isinstance(out, dict):\n status = _valid(status, out=out)\n else:\n if out.get('merged_statuses', False):\n status = out\n else:\n status = _set_status(status,\n status=out.get('status', True),\n comment=out.get('comment', ''),\n out=out.get('out', out))\n except Exception:\n trace = traceback.format_exc(None)\n LOG.error(trace)\n _invalid(status)\n LOG.clear()\n # before returning, trying to compact the log output\n for k in ['comment', 'out', 'outlog']:\n if status[k] and isinstance(status[k], six.string_types):\n status[k] = '\\n'.join([\n log\n for log in status[k].split('\\n')\n if log.strip()])\n return status\n", "def info(self, msg):\n self._log('info', msg)\n" ]
# -*- coding: utf-8 -*- ''' Management of zc.buildout .. versionadded:: 2014.1.0 .. _`minitage's buildout maker`: https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py This module is inspired by `minitage's buildout maker`_ .. note:: The zc.buildout integration is still in beta; the API is subject to change General notes ------------- You have those following methods: * upgrade_bootstrap * bootstrap * run_buildout * buildout ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging import sys import traceback import copy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError INVALID_RESPONSE = 'We did not get any expectable answer from buildout' VALID_RESPONSE = '' NOTSET = object() HR = '{0}\n'.format('-' * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { 'status': None, 'logs': [], 'comment': '', 'out': None, 'logs_by_level': {}, 'outlog': None, 'outlog_by_level': None, } _URL_VERSIONS = { 1: 'http://downloads.buildout.org/1/bootstrap.py', 2: 'http://downloads.buildout.org/2/bootstrap.py', } DEFAULT_VER = 2 _logger = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'buildout' def __virtual__(): ''' Only load if buildout libs are present ''' return __virtualname__ def _salt_callback(func, **kwargs): LOG.clear() def _call_callback(*a, **kw): # cleanup the module kwargs before calling it from the # decorator kw = copy.deepcopy(kw) for k in [ar for ar in kw if '__pub' in ar]: kw.pop(k, None) st = BASE_STATUS.copy() directory = kw.get('directory', '.') onlyif = kw.get('onlyif', None) unless = kw.get('unless', None) runas = kw.get('runas', None) env = kw.get('env', ()) status = BASE_STATUS.copy() try: # may rise _ResultTransmission status = _check_onlyif_unless(onlyif, unless, directory=directory, runas=runas, env=env) # if onlyif/unless returns, we are done if status is None: status = BASE_STATUS.copy() comment, st = '', True out = func(*a, **kw) # we may have already final statuses not to be touched # merged_statuses flag is there to check that ! if not isinstance(out, dict): status = _valid(status, out=out) else: if out.get('merged_statuses', False): status = out else: status = _set_status(status, status=out.get('status', True), comment=out.get('comment', ''), out=out.get('out', out)) except Exception: trace = traceback.format_exc(None) LOG.error(trace) _invalid(status) LOG.clear() # before returning, trying to compact the log output for k in ['comment', 'out', 'outlog']: if status[k] and isinstance(status[k], six.string_types): status[k] = '\n'.join([ log for log in status[k].split('\n') if log.strip()]) return status _call_callback.__doc__ = func.__doc__ return _call_callback class _Logger(object): levels = ('info', 'warn', 'debug', 'error') def __init__(self): self._msgs = [] self._by_level = {} def _log(self, level, msg): if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') if level not in self._by_level: self._by_level[level] = [] self._msgs.append((level, msg)) self._by_level[level].append(msg) def debug(self, msg): self._log('debug', msg) def info(self, msg): self._log('info', msg) def error(self, msg): self._log('error', msg) def warn(self, msg): self._log('warn', msg) warning = warn def clear(self): for i in self._by_level: self._by_level[i] = [] for i in range(len(self._msgs)): self._msgs.pop() def get_logs(self, level): return self._by_level.get(level, []) @property def messages(self): return self._msgs @property def by_level(self): return self._by_level LOG = _Logger() def _encode_string(string): if isinstance(string, six.text_type): string = string.encode('utf-8') return string def _encode_status(status): status['out'] = _encode_string(status['out']) status['outlog_by_level'] = _encode_string(status['outlog_by_level']) if status['logs']: for i, data in enumerate(status['logs'][:]): status['logs'][i] = (data[0], _encode_string(data[1])) for logger in 'error', 'warn', 'info', 'debug': logs = status['logs_by_level'].get(logger, [])[:] if logs: for i, log in enumerate(logs): status['logs_by_level'][logger][i] = _encode_string(log) return status def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): ''' Assign status data to a dict. ''' m['out'] = out m['status'] = status m['logs'] = LOG.messages[:] m['logs_by_level'] = LOG.by_level.copy() outlog, outlog_by_level = '', '' m['comment'] = comment if out and isinstance(out, six.string_types): outlog += HR outlog += 'OUTPUT:\n' outlog += '{0}\n'.format(_encode_string(out)) outlog += HR if m['logs']: outlog += HR outlog += 'Log summary:\n' outlog += HR outlog_by_level += HR outlog_by_level += 'Log summary by level:\n' outlog_by_level += HR for level, msg in m['logs']: outlog += '\n{0}: {1}\n'.format(level.upper(), _encode_string(msg)) for logger in 'error', 'warn', 'info', 'debug': logs = m['logs_by_level'].get(logger, []) if logs: outlog_by_level += '\n{0}:\n'.format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = _encode_string(log) outlog_by_level += '\n'.join(logs) outlog_by_level += '\n' outlog += HR m['outlog'] = outlog m['outlog_by_level'] = outlog_by_level return _encode_status(m) def _invalid(m, comment=INVALID_RESPONSE, out=None): ''' Return invalid status. ''' return _set_status(m, status=False, comment=comment, out=out) def _valid(m, comment=VALID_RESPONSE, out=None): ''' Return valid status. ''' return _set_status(m, status=True, comment=comment, out=out) def _Popen(command, output=False, directory='.', runas=None, env=(), exitcode=0, use_vt=False, loglevel=None): ''' Run a command. output return output if true directory directory to execute in runas user used to run buildout as env environment variables to set when running exitcode fails if cmd does not return this exit code (set to None to disable check) use_vt Use the new salt VT to stream output [experimental] ''' ret = None directory = os.path.abspath(directory) if isinstance(command, list): command = ' '.join(command) LOG.debug('Running {0}'.format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = 'debug' ret = __salt__['cmd.run_all']( command, cwd=directory, output_loglevel=loglevel, runas=runas, env=env, use_vt=use_vt, python_shell=False) out = ret['stdout'] + '\n\n' + ret['stderr'] if (exitcode is not None) and (ret['retcode'] != exitcode): raise _BuildoutError(out) ret['output'] = out if output: ret = out return ret class _BuildoutError(CommandExecutionError): ''' General Buildout Error. ''' def _has_old_distribute(python=sys.executable, runas=None, env=()): old_distribute = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print pkg_resources.' 'get_distribution(\"distribute\").location\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'distribute-0.6' in ret: old_distribute = True except Exception: old_distribute = False return old_distribute def _has_setuptools7(python=sys.executable, runas=None, env=()): new_st = False try: cmd = [python, '-c', '\'import pkg_resources;' 'print not pkg_resources.' 'get_distribution("setuptools").version.startswith("0.6")\''] ret = _Popen(cmd, runas=runas, env=env, output=True) if 'true' in ret.lower(): new_st = True except Exception: new_st = False return new_st def _find_cfgs(path, cfgs=None): ''' Find all buildout configs in a subdirectory. only buildout.cfg and etc/buildout.cfg are valid in:: path directory where to start to search cfg a optional list to append to . ├── buildout.cfg ├── etc │   └── buildout.cfg ├── foo │   └── buildout.cfg └── var └── buildout.cfg ''' ignored = ['var', 'parts'] dirs = [] if not cfgs: cfgs = [] for i in os.listdir(path): fi = os.path.join(path, i) if fi.endswith('.cfg') and os.path.isfile(fi): cfgs.append(fi) if os.path.isdir(fi) and (i not in ignored): dirs.append(fi) for fpath in dirs: for p, ids, ifs in salt.utils.path.os_walk(fpath): for i in ifs: if i.endswith('.cfg'): cfgs.append(os.path.join(p, i)) return cfgs def _get_bootstrap_content(directory='.'): ''' Get the current bootstrap.py script content ''' try: with salt.utils.files.fopen(os.path.join( os.path.abspath(directory), 'bootstrap.py')) as fic: oldcontent = salt.utils.stringutils.to_unicode( fic.read() ) except (OSError, IOError): oldcontent = '' return oldcontent def _get_buildout_ver(directory='.'): '''Check for buildout versions. In any cases, check for a version pinning Also check for buildout.dumppickedversions which is buildout1 specific Also check for the version targeted by the local bootstrap file Take as default buildout2 directory directory to execute in ''' directory = os.path.abspath(directory) buildoutver = 2 try: files = _find_cfgs(directory) for f in files: with salt.utils.files.fopen(f) as fic: buildout1re = re.compile(r'^zc\.buildout\s*=\s*1', RE_F) dfic = salt.utils.stringutils.to_unicode(fic.read()) if ( ('buildout.dumppick' in dfic) or (buildout1re.search(dfic)) ): buildoutver = 1 bcontent = _get_bootstrap_content(directory) if ( '--download-base' in bcontent or '--setup-source' in bcontent or '--distribute' in bcontent ): buildoutver = 1 except (OSError, IOError): pass return buildoutver def _get_bootstrap_url(directory): ''' Get the most appropriate download URL for the bootstrap script. directory directory to execute in ''' v = _get_buildout_ver(directory) return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) def _dot_buildout(directory): ''' Get the local marker directory. directory directory to execute in ''' return os.path.join( os.path.abspath(directory), '.buildout') @_salt_callback def upgrade_bootstrap(directory='.', onlyif=None, unless=None, runas=None, env=(), offline=False, buildout_ver=None): ''' Upgrade current bootstrap.py with the last released one. Indeed, when we first run a buildout, a common source of problem is to have a locally stale bootstrap, we just try to grab a new copy directory directory to execute in offline are we executing buildout in offline mode buildout_ver forcing to use a specific buildout version (1 | 2) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 CLI Example: .. code-block:: bash salt '*' buildout.upgrade_bootstrap /srv/mybuildout ''' if buildout_ver: booturl = _URL_VERSIONS[buildout_ver] else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) LOG.debug('Using {0}'.format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content directory = os.path.abspath(directory) b_py = os.path.join(directory, 'bootstrap.py') comment = '' try: oldcontent = _get_bootstrap_content(directory) dbuild = _dot_buildout(directory) data = oldcontent updated = False dled = False if not offline: try: if not os.path.isdir(dbuild): os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen(os.path.join( dbuild, '{0}.updated_bootstrap'.format(buildout_ver))): pass except (OSError, IOError): LOG.info('Bootstrap updated from repository') data = _urlopen(booturl).read() updated = True dled = True if 'socket.setdefaulttimeout' not in data: updated = True ldata = data.splitlines() ldata.insert(1, 'import socket;socket.setdefaulttimeout(2)') data = '\n'.join(ldata) if updated: comment = 'Bootstrap updated' with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen(os.path.join(dbuild, '{0}.updated_bootstrap'.format( buildout_ver)), 'w') as afic: afic.write('foo') except (OSError, IOError): if oldcontent: with salt.utils.files.fopen(b_py, 'w') as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) return {'comment': comment} @_salt_callback def bootstrap(directory='.', config='buildout.cfg', python=sys.executable, onlyif=None, unless=None, runas=None, env=(), distribute=None, buildout_ver=None, test_release=False, offline=False, new_st=None, use_vt=False, loglevel=None): ''' Run the buildout bootstrap dance (python bootstrap.py). directory directory to execute in config alternative buildout configuration file to use runas User used to run buildout as env environment variables to set when running buildout_ver force a specific buildout version (1 | 2) test_release buildout accept test release offline are we executing buildout in offline mode distribute Forcing use of distribute new_st Forcing use of setuptools >= 0.7 python path to a python executable to use in place of default (salt one) onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.bootstrap /srv/mybuildout ''' directory = os.path.abspath(directory) dbuild = _dot_buildout(directory) bootstrap_args = '' has_distribute = _has_old_distribute(python=python, runas=runas, env=env) has_new_st = _has_setuptools7(python=python, runas=runas, env=env) if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and distribute and not new_st ): new_st = True distribute = False if ( not has_distribute and has_new_st and not distribute and not new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( has_distribute and not has_new_st and not distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and not distribute and new_st ): new_st = True distribute = False if ( not has_distribute and not has_new_st and distribute and not new_st ): new_st = False distribute = True if ( not has_distribute and not has_new_st and not distribute and not new_st ): new_st = True distribute = False if new_st and distribute: distribute = False if new_st: distribute = False LOG.warning('Forcing to use setuptools as we have setuptools >= 0.7') if distribute: new_st = False if buildout_ver == 1: LOG.warning('Using distribute !') bootstrap_args += ' --distribute' if not os.path.isdir(dbuild): os.makedirs(dbuild) upgrade_bootstrap(directory, offline=offline, buildout_ver=buildout_ver) # be sure which buildout bootstrap we have b_py = os.path.join(directory, 'bootstrap.py') with salt.utils.files.fopen(b_py) as fic: content = salt.utils.stringutils.to_unicode(fic.read()) if ( (test_release is not False) and ' --accept-buildout-test-releases' in content ): bootstrap_args += ' --accept-buildout-test-releases' if config and '"-c"' in content: bootstrap_args += ' -c {0}'.format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__['user.info'](runas)['uid'] gid = __salt__['user.info'](runas)['gid'] os.chown('bootstrap.py', uid, gid) except (IOError, OSError) as exc: # don't block here, try to execute it if can pass _logger.error('BUILDOUT bootstrap permissions error: %s', exc, exc_info=_logger.isEnabledFor(logging.DEBUG)) cmd = '{0} bootstrap.py {1}'.format(python, bootstrap_args) ret = _Popen(cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt) output = ret['output'] return {'comment': cmd, 'out': output} @_salt_callback def run_buildout(directory='.', config='buildout.cfg', parts=None, onlyif=None, unless=None, offline=False, newest=True, runas=None, env=(), verbose=False, debug=False, use_vt=False, loglevel=None): ''' Run a buildout in a directory. directory directory to execute in config alternative buildout configuration file to use offline are we executing buildout in offline mode runas user used to run buildout as env environment variables to set when running onlyif Only execute cmd if statement on the host return 0 unless Do not execute cmd if statement on the host return 0 newest run buildout in newest mode force run buildout unconditionally verbose run buildout in verbose mode (-vvvvv) use_vt Use the new salt VT to stream output [experimental] CLI Example: .. code-block:: bash salt '*' buildout.run_buildout /srv/mybuildout ''' directory = os.path.abspath(directory) bcmd = os.path.join(directory, 'bin', 'buildout') installed_cfg = os.path.join(directory, '.installed.cfg') argv = [] if verbose: LOG.debug('Buildout is running in verbose mode!') argv.append('-vvvvvvv') if not newest and os.path.exists(installed_cfg): LOG.debug('Buildout is running in non newest mode!') argv.append('-N') if newest: LOG.debug('Buildout is running in newest mode!') argv.append('-n') if offline: LOG.debug('Buildout is running in offline mode!') argv.append('-o') if debug: LOG.debug('Buildout is running in debug mode!') argv.append('-D') cmds, outputs = [], [] if parts: for part in parts: LOG.info('Installing single part: {0}'.format(part)) # pylint: disable=str-format-in-logging cmd = '{0} -c {1} {2} install {3}'.format( bcmd, config, ' '.join(argv), part) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, env=env, output=True, loglevel=loglevel, use_vt=use_vt) ) else: LOG.info('Installing all buildout parts') cmd = '{0} -c {1} {2}'.format( bcmd, config, ' '.join(argv)) cmds.append(cmd) outputs.append( _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, output=True, use_vt=use_vt) ) return {'comment': '\n'.join(cmds), 'out': '\n'.join(outputs)} def _merge_statuses(statuses): status = BASE_STATUS.copy() status['status'] = None status['merged_statuses'] = True status['out'] = [] for st in statuses: if status['status'] is not False: status['status'] = st['status'] out = st['out'] comment = _encode_string(st['comment']) logs = st['logs'] logs_by_level = st['logs_by_level'] outlog_by_level = st['outlog_by_level'] outlog = st['outlog'] if out: if not status['out']: status['out'] = '' status['out'] += '\n' status['out'] += HR out = _encode_string(out) status['out'] += '{0}\n'.format(out) status['out'] += HR if comment: if not status['comment']: status['comment'] = '' status['comment'] += '\n{0}\n'.format( _encode_string(comment)) if outlog: if not status['outlog']: status['outlog'] = '' outlog = _encode_string(outlog) status['outlog'] += '\n{0}'.format(HR) status['outlog'] += outlog if outlog_by_level: if not status['outlog_by_level']: status['outlog_by_level'] = '' status['outlog_by_level'] += '\n{0}'.format(HR) status['outlog_by_level'] += _encode_string(outlog_by_level) status['logs'].extend([ (a[0], _encode_string(a[1])) for a in logs]) for log in logs_by_level: if log not in status['logs_by_level']: status['logs_by_level'][log] = [] status['logs_by_level'][log].extend( [_encode_string(a) for a in logs_by_level[log]]) return _encode_status(status) @_salt_callback def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): ret = None status = BASE_STATUS.copy() if os.path.exists(directory): directory = os.path.abspath(directory) status['status'] = False retcode = __salt__['cmd.retcode'] if onlyif is not None: if not isinstance(onlyif, six.string_types): if not onlyif: _valid(status, 'onlyif condition is false') elif isinstance(onlyif, six.string_types): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, 'onlyif condition is false') if unless is not None: if not isinstance(unless, six.string_types): if unless: _valid(status, 'unless condition is true') elif isinstance(unless, six.string_types): if retcode(unless, cwd=directory, runas=runas, env=env, python_shell=False) == 0: _valid(status, 'unless condition is true') if status['status']: ret = status return ret # vim:set et sts=4 ts=4 tw=80:
saltstack/salt
salt/pillar/sqlite3.py
ext_pillar
python
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Execute queries against SQLite3, merge and return as a dict ''' return SQLite3ExtPillar().fetch(minion_id, pillar, *args, **kwargs)
Execute queries against SQLite3, merge and return as a dict
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sqlite3.py#L110-L117
null
# -*- coding: utf-8 -*- ''' Retrieve Pillar data by doing a SQLite3 query .. versionadded:: 2015.8.0 ``sqlite3`` is included in the stdlib since Python 2.5. This module is a concrete implementation of the sql_base ext_pillar for SQLite3. :platform: all Configuring the sqlite3 ext_pillar ================================== Use the 'sqlite3' key under ext_pillar for configuration of queries. SQLite3 database connection configuration requires the following values configured in the master config: Note, timeout is in seconds. .. code-block:: yaml sqlite3.database: /var/lib/salt/pillar.db sqlite3.timeout: 5.0 Complete Example ================ .. code-block:: yaml sqlite3: database: '/var/lib/salt/pillar.db' timeout: 5.0 ext_pillar: - sqlite3: fromdb: query: 'SELECT col1,col2,col3,col4,col5,col6,col7 FROM some_random_table WHERE minion_pattern LIKE ?' depth: 5 as_list: True with_lists: [1,3] ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs from contextlib import contextmanager import logging import sqlite3 # Import Salt libs from salt.pillar.sql_base import SqlBaseExtPillar # Set up logging log = logging.getLogger(__name__) def __virtual__(): return True class SQLite3ExtPillar(SqlBaseExtPillar): ''' This class receives and processes the database rows from SQLite3. ''' @classmethod def _db_name(cls): return 'SQLite3' def _get_options(self): ''' Returns options used for the SQLite3 connection. ''' defaults = {'database': '/var/lib/salt/pillar.db', 'timeout': 5.0} _options = {} _opts = {} if 'sqlite3' in __opts__ and 'database' in __opts__['sqlite3']: _opts = __opts__.get('sqlite3', {}) for attr in defaults: if attr not in _opts: log.debug('Using default for SQLite3 pillar %s', attr) _options[attr] = defaults[attr] continue _options[attr] = _opts[attr] return _options @contextmanager def _get_cursor(self): ''' Yield a SQLite3 cursor ''' _options = self._get_options() conn = sqlite3.connect(_options.get('database'), timeout=float(_options.get('timeout'))) cursor = conn.cursor() try: yield cursor except sqlite3.Error as err: log.exception('Error in ext_pillar SQLite3: %s', err.args) finally: conn.close()
saltstack/salt
salt/pillar/http_json.py
ext_pillar
python
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 url, with_grains=False): ''' Read pillar data from HTTP response. :param str url: Url to request. :param bool with_grains: Whether to substitute strings in the url with their grain values. :return: A dictionary of the pillar data to add. :rtype: dict ''' url = url.replace('%s', _quote(minion_id)) grain_pattern = r'<(?P<grain_name>.*?)>' if with_grains: # Get the value of the grain and substitute each grain # name for the url-encoded version of its grain value. for match in re.finditer(grain_pattern, url): grain_name = match.group('grain_name') grain_value = __salt__['grains.get'](grain_name, None) if not grain_value: log.error("Unable to get minion '%s' grain: %s", minion_id, grain_name) return {} grain_value = _quote(six.text_type(grain_value)) url = re.sub('<{0}>'.format(grain_name), grain_value, url) log.debug('Getting url: %s', url) data = __salt__['http.query'](url=url, decode=True, decode_type='json') if 'dict' in data: return data['dict'] log.error("Error on minion '%s' http query: %s\nMore Info:\n", minion_id, url) for key in data: log.error('%s: %s', key, data[key]) return {}
Read pillar data from HTTP response. :param str url: Url to request. :param bool with_grains: Whether to substitute strings in the url with their grain values. :return: A dictionary of the pillar data to add. :rtype: dict
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/http_json.py#L66-L109
null
# -*- coding: utf-8 -*- ''' A module that adds data to the Pillar structure retrieved by an http request Configuring the HTTP_JSON ext_pillar ==================================== Set the following Salt config to setup http json result as external pillar source: .. code-block:: yaml ext_pillar: - http_json: url: http://example.com/api/minion_id ::TODO:: username: username password: password If the with_grains parameter is set, grain keys wrapped in can be provided (wrapped in <> brackets) in the url in order to populate pillar data based on the grain value. .. code-block:: yaml ext_pillar: - http_json: url: http://example.com/api/<nodename> with_grains: True .. versionchanged:: 2018.3.0 If %s is present in the url, it will be automatically replaced by the minion_id: .. code-block:: yaml ext_pillar: - http_json: url: http://example.com/api/%s Module Documentation ==================== ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re from salt.ext import six # Import Salt libs try: from salt.ext.six.moves.urllib.parse import quote as _quote _HAS_DEPENDENCIES = True except ImportError: _HAS_DEPENDENCIES = False # Set up logging log = logging.getLogger(__name__) def __virtual__(): return _HAS_DEPENDENCIES
saltstack/salt
salt/modules/nxos.py
check_password
python
def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False
Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L143-L181
[ "def get_user(username, **kwargs):\n '''\n Get username line from switch.\n\n .. code-block: bash\n\n salt '*' nxos.cmd get_user username=admin\n '''\n command = 'show run | include \"^username {0} password 5 \"'.format(username)\n info = ''\n info = show(command, **kwargs)\n if isinstance(info, list):\n info = info[0]\n return info\n", "def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):\n '''\n Generate /etc/shadow hash\n '''\n if not HAS_CRYPT:\n raise SaltInvocationError('No crypt module for windows')\n\n hash_algorithms = dict(\n md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'\n )\n if algorithm not in hash_algorithms:\n raise SaltInvocationError(\n 'Algorithm \\'{0}\\' is not supported'.format(algorithm)\n )\n\n if password is None:\n password = secure_password()\n\n if crypt_salt is None:\n crypt_salt = secure_password(8)\n\n crypt_salt = hash_algorithms[algorithm] + crypt_salt\n\n return crypt.crypt(password, crypt_salt)\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
cmd
python
def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs)
NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L195-L228
null
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
get_roles
python
def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles
Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L247-L268
[ "def show(commands, raw_text=True, **kwargs):\n '''\n Execute one or more show (non-configuration) commands.\n\n commands\n The commands to be executed.\n\n raw_text: ``True``\n Whether to return raw text or structured data.\n NOTE: raw_text option is ignored for SSH proxy minion. Data is\n returned unstructured.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call --local nxos.show 'show version'\n salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False\n salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test\n '''\n if not isinstance(raw_text, bool):\n msg = \"\"\"\n INPUT ERROR: Second argument 'raw_text' must be either True or False\n Value passed: {0}\n Hint: White space separated show commands should be wrapped by double quotes\n \"\"\".format(raw_text)\n return msg\n\n if raw_text:\n method = 'cli_show_ascii'\n else:\n method = 'cli_show'\n\n response_list = sendline(commands, method, **kwargs)\n if isinstance(response_list, list):\n ret = [response for response in response_list if response]\n if not ret:\n ret = ['']\n return ret\n else:\n return response_list\n", "def get_user(username, **kwargs):\n '''\n Get username line from switch.\n\n .. code-block: bash\n\n salt '*' nxos.cmd get_user username=admin\n '''\n command = 'show run | include \"^username {0} password 5 \"'.format(username)\n info = ''\n info = show(command, **kwargs)\n if isinstance(info, list):\n info = info[0]\n return info\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
get_user
python
def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L271-L284
[ "def show(commands, raw_text=True, **kwargs):\n '''\n Execute one or more show (non-configuration) commands.\n\n commands\n The commands to be executed.\n\n raw_text: ``True``\n Whether to return raw text or structured data.\n NOTE: raw_text option is ignored for SSH proxy minion. Data is\n returned unstructured.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call --local nxos.show 'show version'\n salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False\n salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test\n '''\n if not isinstance(raw_text, bool):\n msg = \"\"\"\n INPUT ERROR: Second argument 'raw_text' must be either True or False\n Value passed: {0}\n Hint: White space separated show commands should be wrapped by double quotes\n \"\"\".format(raw_text)\n return msg\n\n if raw_text:\n method = 'cli_show_ascii'\n else:\n method = 'cli_show'\n\n response_list = sendline(commands, method, **kwargs)\n if isinstance(response_list, list):\n ret = [response for response in response_list if response]\n if not ret:\n ret = ['']\n return ret\n else:\n return response_list\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
grains
python
def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache']
Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L287-L299
[ "def system_info(data):\n '''\n Helper method to return parsed system_info\n from the 'show version' command.\n '''\n if not data:\n return {}\n info = {\n 'software': _parse_software(data),\n 'hardware': _parse_hardware(data),\n 'plugins': _parse_plugins(data),\n }\n return {'nxos': info}\n", "def show_ver(**kwargs):\n '''\n Shortcut to run `show version` on the NX-OS device.\n\n .. code-block:: bash\n\n salt '*' nxos.cmd show_ver\n '''\n command = 'show version'\n info = ''\n info = show(command, **kwargs)\n if isinstance(info, list):\n info = info[0]\n return info\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
sendline
python
def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs)
Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L314-L345
[ "def _nxapi_request(commands,\n method='cli_conf',\n **kwargs):\n '''\n Helper function to send exec and config requests over NX-API.\n\n commands\n The exec or config commands to be sent.\n\n method: ``cli_show``\n ``cli_show_ascii``: Return raw test or unstructured output.\n ``cli_show``: Return structured output.\n ``cli_conf``: Send configuration commands to the device.\n Defaults to ``cli_conf``.\n '''\n if salt.utils.platform.is_proxy():\n return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs)\n else:\n api_kwargs = __salt__['config.get']('nxos', {})\n api_kwargs.update(**kwargs)\n return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
show
python
def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list
Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L348-L388
[ "def sendline(command, method='cli_show_ascii', **kwargs):\n '''\n Send arbitray commands to the NX-OS device.\n\n command\n The command to be sent.\n\n method:\n ``cli_show_ascii``: Return raw test or unstructured output.\n ``cli_show``: Return structured output.\n ``cli_conf``: Send configuration commands to the device.\n Defaults to ``cli_show_ascii``.\n NOTE: method is ignored for SSH proxy minion. All data is returned\n unstructured.\n\n .. code-block: bash\n\n salt '*' nxos.cmd sendline 'show run | include \"^username admin password\"'\n '''\n smethods = ['cli_show_ascii', 'cli_show', 'cli_conf']\n if method not in smethods:\n msg = \"\"\"\n INPUT ERROR: Second argument 'method' must be one of {0}\n Value passed: {1}\n Hint: White space separated commands should be wrapped by double quotes\n \"\"\".format(smethods, method)\n return msg\n\n if salt.utils.platform.is_proxy():\n return __proxy__['nxos.sendline'](command, method, **kwargs)\n else:\n return _nxapi_request(command, method, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
show_ver
python
def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L391-L404
[ "def show(commands, raw_text=True, **kwargs):\n '''\n Execute one or more show (non-configuration) commands.\n\n commands\n The commands to be executed.\n\n raw_text: ``True``\n Whether to return raw text or structured data.\n NOTE: raw_text option is ignored for SSH proxy minion. Data is\n returned unstructured.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call --local nxos.show 'show version'\n salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False\n salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test\n '''\n if not isinstance(raw_text, bool):\n msg = \"\"\"\n INPUT ERROR: Second argument 'raw_text' must be either True or False\n Value passed: {0}\n Hint: White space separated show commands should be wrapped by double quotes\n \"\"\".format(raw_text)\n return msg\n\n if raw_text:\n method = 'cli_show_ascii'\n else:\n method = 'cli_show'\n\n response_list = sendline(commands, method, **kwargs)\n if isinstance(response_list, list):\n ret = [response for response in response_list if response]\n if not ret:\n ret = ['']\n return ret\n else:\n return response_list\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
show_run
python
def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info
Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L407-L420
[ "def show(commands, raw_text=True, **kwargs):\n '''\n Execute one or more show (non-configuration) commands.\n\n commands\n The commands to be executed.\n\n raw_text: ``True``\n Whether to return raw text or structured data.\n NOTE: raw_text option is ignored for SSH proxy minion. Data is\n returned unstructured.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call --local nxos.show 'show version'\n salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False\n salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test\n '''\n if not isinstance(raw_text, bool):\n msg = \"\"\"\n INPUT ERROR: Second argument 'raw_text' must be either True or False\n Value passed: {0}\n Hint: White space separated show commands should be wrapped by double quotes\n \"\"\".format(raw_text)\n return msg\n\n if raw_text:\n method = 'cli_show_ascii'\n else:\n method = 'cli_show'\n\n response_list = sendline(commands, method, **kwargs)\n if isinstance(response_list, list):\n ret = [response for response in response_list if response]\n if not ret:\n ret = ['']\n return ret\n else:\n return response_list\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
config
python
def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff
Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L459-L556
[ "def show(commands, raw_text=True, **kwargs):\n '''\n Execute one or more show (non-configuration) commands.\n\n commands\n The commands to be executed.\n\n raw_text: ``True``\n Whether to return raw text or structured data.\n NOTE: raw_text option is ignored for SSH proxy minion. Data is\n returned unstructured.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call --local nxos.show 'show version'\n salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False\n salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test\n '''\n if not isinstance(raw_text, bool):\n msg = \"\"\"\n INPUT ERROR: Second argument 'raw_text' must be either True or False\n Value passed: {0}\n Hint: White space separated show commands should be wrapped by double quotes\n \"\"\".format(raw_text)\n return msg\n\n if raw_text:\n method = 'cli_show_ascii'\n else:\n method = 'cli_show'\n\n response_list = sendline(commands, method, **kwargs)\n if isinstance(response_list, list):\n ret = [response for response in response_list if response]\n if not ret:\n ret = ['']\n return ret\n else:\n return response_list\n", "def _parse_config_result(data):\n command_list = ' ; '.join([x.strip() for x in data[0]])\n config_result = data[1]\n if isinstance(config_result, list):\n result = ''\n if isinstance(config_result[0], dict):\n for key in config_result[0]:\n result += config_result[0][key]\n config_result = result\n else:\n config_result = config_result[0]\n return [command_list, config_result]\n", "def _configure_device(commands, **kwargs):\n '''\n Helper function to send configuration commands to the device over a\n proxy minion or native minion using NX-API or SSH.\n '''\n if salt.utils.platform.is_proxy():\n return __proxy__['nxos.proxy_config'](commands, **kwargs)\n else:\n return _nxapi_config(commands, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
delete_config
python
def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result
Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L573-L604
[ "def config(commands=None,\n config_file=None,\n template_engine='jinja',\n context=None,\n defaults=None,\n saltenv='base',\n **kwargs):\n '''\n Configures the Nexus switch with the specified commands.\n\n This method is used to send configuration commands to the switch. It\n will take either a string or a list and prepend the necessary commands\n to put the session into config mode.\n\n .. warning::\n\n All the commands will be applied directly to the running-config.\n\n config_file\n The source file with the configuration commands to be sent to the\n device.\n\n The file can also be a template that can be rendered using the template\n engine of choice.\n\n This can be specified using the absolute path to the file, or using one\n of the following URL schemes:\n\n - ``salt://``, to fetch the file from the Salt fileserver.\n - ``http://`` or ``https://``\n - ``ftp://``\n - ``s3://``\n - ``swift://``\n\n commands\n The commands to send to the switch in config mode. If the commands\n argument is a string it will be cast to a list.\n The list of commands will also be prepended with the necessary commands\n to put the session in config mode.\n\n .. note::\n\n This argument is ignored when ``config_file`` is specified.\n\n template_engine: ``jinja``\n The template engine to use when rendering the source file. Default:\n ``jinja``. To simply fetch the file without attempting to render, set\n this argument to ``None``.\n\n context\n Variables to add to the template context.\n\n defaults\n Default values of the context_dict.\n\n no_save_config\n If True, don't save configuration commands to startup configuration.\n If False, save configuration to startup configuration.\n Default: False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nxos.config commands=\"['spanning-tree mode mstp']\"\n salt '*' nxos.config config_file=salt://config.txt\n salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context=\"{'servers': ['1.2.3.4']}\"\n '''\n initial_config = show('show running-config', **kwargs)\n if isinstance(initial_config, list):\n initial_config = initial_config[0]\n if config_file:\n file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv)\n if file_str is False:\n raise CommandExecutionError('Source file {} not found'.format(config_file))\n elif commands:\n if isinstance(commands, (six.string_types, six.text_type)):\n commands = [commands]\n file_str = '\\n'.join(commands)\n # unify all the commands in a single file, to render them in a go\n if template_engine:\n file_str = __salt__['file.apply_template_on_contents'](file_str,\n template_engine,\n context,\n defaults,\n saltenv)\n # whatever the source of the commands would be, split them line by line\n commands = [line for line in file_str.splitlines() if line.strip()]\n config_result = _parse_config_result(_configure_device(commands, **kwargs))\n current_config = show('show running-config', **kwargs)\n if isinstance(current_config, list):\n current_config = current_config[0]\n diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:])\n clean_diff = ''.join([x.replace('\\r', '') for x in diff])\n head = 'COMMAND_LIST: '\n cc = config_result[0]\n cr = config_result[1]\n return head + cc + '\\n' + cr + '\\n' + clean_diff\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
set_password
python
def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs)
Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L667-L723
[ "def config(commands=None,\n config_file=None,\n template_engine='jinja',\n context=None,\n defaults=None,\n saltenv='base',\n **kwargs):\n '''\n Configures the Nexus switch with the specified commands.\n\n This method is used to send configuration commands to the switch. It\n will take either a string or a list and prepend the necessary commands\n to put the session into config mode.\n\n .. warning::\n\n All the commands will be applied directly to the running-config.\n\n config_file\n The source file with the configuration commands to be sent to the\n device.\n\n The file can also be a template that can be rendered using the template\n engine of choice.\n\n This can be specified using the absolute path to the file, or using one\n of the following URL schemes:\n\n - ``salt://``, to fetch the file from the Salt fileserver.\n - ``http://`` or ``https://``\n - ``ftp://``\n - ``s3://``\n - ``swift://``\n\n commands\n The commands to send to the switch in config mode. If the commands\n argument is a string it will be cast to a list.\n The list of commands will also be prepended with the necessary commands\n to put the session in config mode.\n\n .. note::\n\n This argument is ignored when ``config_file`` is specified.\n\n template_engine: ``jinja``\n The template engine to use when rendering the source file. Default:\n ``jinja``. To simply fetch the file without attempting to render, set\n this argument to ``None``.\n\n context\n Variables to add to the template context.\n\n defaults\n Default values of the context_dict.\n\n no_save_config\n If True, don't save configuration commands to startup configuration.\n If False, save configuration to startup configuration.\n Default: False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nxos.config commands=\"['spanning-tree mode mstp']\"\n salt '*' nxos.config config_file=salt://config.txt\n salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context=\"{'servers': ['1.2.3.4']}\"\n '''\n initial_config = show('show running-config', **kwargs)\n if isinstance(initial_config, list):\n initial_config = initial_config[0]\n if config_file:\n file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv)\n if file_str is False:\n raise CommandExecutionError('Source file {} not found'.format(config_file))\n elif commands:\n if isinstance(commands, (six.string_types, six.text_type)):\n commands = [commands]\n file_str = '\\n'.join(commands)\n # unify all the commands in a single file, to render them in a go\n if template_engine:\n file_str = __salt__['file.apply_template_on_contents'](file_str,\n template_engine,\n context,\n defaults,\n saltenv)\n # whatever the source of the commands would be, split them line by line\n commands = [line for line in file_str.splitlines() if line.strip()]\n config_result = _parse_config_result(_configure_device(commands, **kwargs))\n current_config = show('show running-config', **kwargs)\n if isinstance(current_config, list):\n current_config = current_config[0]\n diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:])\n clean_diff = ''.join([x.replace('\\r', '') for x in diff])\n head = 'COMMAND_LIST: '\n cc = config_result[0]\n cr = config_result[1]\n return head + cc + '\\n' + cr + '\\n' + clean_diff\n", "def get_user(username, **kwargs):\n '''\n Get username line from switch.\n\n .. code-block: bash\n\n salt '*' nxos.cmd get_user username=admin\n '''\n command = 'show run | include \"^username {0} password 5 \"'.format(username)\n info = ''\n info = show(command, **kwargs)\n if isinstance(info, list):\n info = info[0]\n return info\n", "def secure_password(length=20, use_random=True):\n '''\n Generate a secure password.\n '''\n try:\n length = int(length)\n pw = ''\n while len(pw) < length:\n if HAS_RANDOM and use_random:\n while True:\n try:\n char = salt.utils.stringutils.to_str(get_random_bytes(1))\n break\n except UnicodeDecodeError:\n continue\n pw += re.sub(\n salt.utils.stringutils.to_str(r'\\W'),\n str(), # future lint: disable=blacklisted-function\n char\n )\n else:\n pw += random.SystemRandom().choice(string.ascii_letters + string.digits)\n return pw\n except Exception as exc:\n log.exception('Failed to generate secure passsword')\n raise CommandExecutionError(six.text_type(exc))\n", "def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):\n '''\n Generate /etc/shadow hash\n '''\n if not HAS_CRYPT:\n raise SaltInvocationError('No crypt module for windows')\n\n hash_algorithms = dict(\n md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'\n )\n if algorithm not in hash_algorithms:\n raise SaltInvocationError(\n 'Algorithm \\'{0}\\' is not supported'.format(algorithm)\n )\n\n if password is None:\n password = secure_password()\n\n if crypt_salt is None:\n crypt_salt = secure_password(8)\n\n crypt_salt = hash_algorithms[algorithm] + crypt_salt\n\n return crypt.crypt(password, crypt_salt)\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
set_role
python
def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs)
Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L726-L746
[ "def config(commands=None,\n config_file=None,\n template_engine='jinja',\n context=None,\n defaults=None,\n saltenv='base',\n **kwargs):\n '''\n Configures the Nexus switch with the specified commands.\n\n This method is used to send configuration commands to the switch. It\n will take either a string or a list and prepend the necessary commands\n to put the session into config mode.\n\n .. warning::\n\n All the commands will be applied directly to the running-config.\n\n config_file\n The source file with the configuration commands to be sent to the\n device.\n\n The file can also be a template that can be rendered using the template\n engine of choice.\n\n This can be specified using the absolute path to the file, or using one\n of the following URL schemes:\n\n - ``salt://``, to fetch the file from the Salt fileserver.\n - ``http://`` or ``https://``\n - ``ftp://``\n - ``s3://``\n - ``swift://``\n\n commands\n The commands to send to the switch in config mode. If the commands\n argument is a string it will be cast to a list.\n The list of commands will also be prepended with the necessary commands\n to put the session in config mode.\n\n .. note::\n\n This argument is ignored when ``config_file`` is specified.\n\n template_engine: ``jinja``\n The template engine to use when rendering the source file. Default:\n ``jinja``. To simply fetch the file without attempting to render, set\n this argument to ``None``.\n\n context\n Variables to add to the template context.\n\n defaults\n Default values of the context_dict.\n\n no_save_config\n If True, don't save configuration commands to startup configuration.\n If False, save configuration to startup configuration.\n Default: False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nxos.config commands=\"['spanning-tree mode mstp']\"\n salt '*' nxos.config config_file=salt://config.txt\n salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context=\"{'servers': ['1.2.3.4']}\"\n '''\n initial_config = show('show running-config', **kwargs)\n if isinstance(initial_config, list):\n initial_config = initial_config[0]\n if config_file:\n file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv)\n if file_str is False:\n raise CommandExecutionError('Source file {} not found'.format(config_file))\n elif commands:\n if isinstance(commands, (six.string_types, six.text_type)):\n commands = [commands]\n file_str = '\\n'.join(commands)\n # unify all the commands in a single file, to render them in a go\n if template_engine:\n file_str = __salt__['file.apply_template_on_contents'](file_str,\n template_engine,\n context,\n defaults,\n saltenv)\n # whatever the source of the commands would be, split them line by line\n commands = [line for line in file_str.splitlines() if line.strip()]\n config_result = _parse_config_result(_configure_device(commands, **kwargs))\n current_config = show('show running-config', **kwargs)\n if isinstance(current_config, list):\n current_config = current_config[0]\n diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:])\n clean_diff = ''.join([x.replace('\\r', '') for x in diff])\n head = 'COMMAND_LIST: '\n cc = config_result[0]\n cr = config_result[1]\n return head + cc + '\\n' + cr + '\\n' + clean_diff\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
unset_role
python
def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs)
Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L749-L769
[ "def config(commands=None,\n config_file=None,\n template_engine='jinja',\n context=None,\n defaults=None,\n saltenv='base',\n **kwargs):\n '''\n Configures the Nexus switch with the specified commands.\n\n This method is used to send configuration commands to the switch. It\n will take either a string or a list and prepend the necessary commands\n to put the session into config mode.\n\n .. warning::\n\n All the commands will be applied directly to the running-config.\n\n config_file\n The source file with the configuration commands to be sent to the\n device.\n\n The file can also be a template that can be rendered using the template\n engine of choice.\n\n This can be specified using the absolute path to the file, or using one\n of the following URL schemes:\n\n - ``salt://``, to fetch the file from the Salt fileserver.\n - ``http://`` or ``https://``\n - ``ftp://``\n - ``s3://``\n - ``swift://``\n\n commands\n The commands to send to the switch in config mode. If the commands\n argument is a string it will be cast to a list.\n The list of commands will also be prepended with the necessary commands\n to put the session in config mode.\n\n .. note::\n\n This argument is ignored when ``config_file`` is specified.\n\n template_engine: ``jinja``\n The template engine to use when rendering the source file. Default:\n ``jinja``. To simply fetch the file without attempting to render, set\n this argument to ``None``.\n\n context\n Variables to add to the template context.\n\n defaults\n Default values of the context_dict.\n\n no_save_config\n If True, don't save configuration commands to startup configuration.\n If False, save configuration to startup configuration.\n Default: False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' nxos.config commands=\"['spanning-tree mode mstp']\"\n salt '*' nxos.config config_file=salt://config.txt\n salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context=\"{'servers': ['1.2.3.4']}\"\n '''\n initial_config = show('show running-config', **kwargs)\n if isinstance(initial_config, list):\n initial_config = initial_config[0]\n if config_file:\n file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv)\n if file_str is False:\n raise CommandExecutionError('Source file {} not found'.format(config_file))\n elif commands:\n if isinstance(commands, (six.string_types, six.text_type)):\n commands = [commands]\n file_str = '\\n'.join(commands)\n # unify all the commands in a single file, to render them in a go\n if template_engine:\n file_str = __salt__['file.apply_template_on_contents'](file_str,\n template_engine,\n context,\n defaults,\n saltenv)\n # whatever the source of the commands would be, split them line by line\n commands = [line for line in file_str.splitlines() if line.strip()]\n config_result = _parse_config_result(_configure_device(commands, **kwargs))\n current_config = show('show running-config', **kwargs)\n if isinstance(current_config, list):\n current_config = current_config[0]\n diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:])\n clean_diff = ''.join([x.replace('\\r', '') for x in diff])\n head = 'COMMAND_LIST: '\n cc = config_result[0]\n cr = config_result[1]\n return head + cc + '\\n' + cr + '\\n' + clean_diff\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
_configure_device
python
def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs)
Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L775-L783
null
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret] def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
_nxapi_config
python
def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret]
Helper function to send configuration commands using NX-API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L786-L806
null
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
saltstack/salt
salt/modules/nxos.py
_nxapi_request
python
def _nxapi_request(commands, method='cli_conf', **kwargs): ''' Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos._nxapi_request'](commands, method=method, **kwargs) else: api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) return __utils__['nxos.nxapi_request'](commands, method=method, **api_kwargs)
Helper function to send exec and config requests over NX-API. commands The exec or config commands to be sent. method: ``cli_show`` ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_conf``.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L809-L829
null
# -*- coding: utf-8 -*- ''' Execution module for Cisco NX OS Switches. .. versionadded:: 2016.11.0 This module supports execution using a Proxy Minion or Native Minion: - Proxy Minion: Connect over SSH or NX-API HTTP(S). - See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details. - Native Minion: Connect over NX-API Unix Domain Socket (UDS). - Install the minion inside the GuestShell running on the NX-OS device. :maturity: new :platform: nxos .. note:: To use this module over remote NX-API the feature must be enabled on the NX-OS device by executing ``feature nxapi`` in configuration mode. This is not required for NX-API over UDS. Configuration example: .. code-block:: bash switch# conf t switch(config)# feature nxapi To check that NX-API is properly enabled, execute ``show nxapi``. Output example: .. code-block:: bash switch# show nxapi nxapi enabled HTTPS Listen on port 443 Native minon configuration options: .. code-block:: yaml nxos: cookie: 'username' no_save_config: True ``cookie`` - Use the option to override the default cookie 'admin:local' when connecting over UDS and use 'username:local' instead. This is needed when running the salt-minion in the GuestShell using a non-admin user. - This option is ignored for SSH and NX-API Proxy minions. ``no_save_config`` - If False, 'copy running-config starting-config' is issues for every configuration command. - If True, Running config is not saved to startup config - Default: False - The recommended approach is to use the `save_running_config` function instead of this option to improve performance. The default behavior controlled by this option is preserved for backwards compatibility. The APIs defined in this execution module can also be executed using salt-call from the GuestShell environment as follows. .. code-block:: bash salt-call --local nxos.show 'show lldp neighbors' raw_text .. note:: The functions in this module can be executed using either of the following syntactic forms. .. code-block:: bash salt '*' nxos.cmd <function> salt '*' nxos.cmd get_user username=admin or .. code-block:: bash salt '*' nxos.<function> salt '*' nxos.get_user username=admin The nxos.cmd <function> syntax is preserved for backwards compatibility. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python stdlib import logging import difflib import re import ast # Import Salt libs from salt.utils.pycrypto import gen_hash, secure_password import salt.utils.platform import salt.utils.nxos from salt.ext import six from salt.exceptions import CommandExecutionError __virtualname__ = 'nxos' log = logging.getLogger(__name__) DEVICE_DETAILS = {'grains_cache': {}} COPY_RS = 'copy running-config startup-config' def __virtual__(): return __virtualname__ def ping(**kwargs): ''' Ping the device on the other end of the connection. .. code-block: bash salt '*' nxos.cmd ping ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.ping']() return __utils__['nxos.ping'](**kwargs) # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def check_password(username, password, encrypted=False, **kwargs): ''' Verify user password. username Username on which to perform password check password Password to check encrypted Whether or not the password is encrypted Default: False .. code-block: bash salt '*' nxos.cmd check_password username=admin password=admin salt '*' nxos.cmd check_password username=admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' hash_algorithms = {'1': 'md5', '2a': 'blowfish', '5': 'sha256', '6': 'sha512', } password_line = get_user(username, **kwargs) if not password_line: return None if '!' in password_line: return False cur_hash = re.search(r'(\$[0-6](?:\$[^$ ]+)+)', password_line).group(0) if encrypted is False: hash_type, cur_salt, hashed_pass = re.search(r'^\$([0-6])\$([^$]+)\$(.*)$', cur_hash).groups() new_hash = gen_hash(crypt_salt=cur_salt, password=password, algorithm=hash_algorithms[hash_type]) else: new_hash = password if new_hash == cur_hash: return True return False def check_role(username, role, **kwargs): ''' Verify role assignment for user. .. code-block:: bash salt '*' nxos.cmd check_role username=admin role=network-admin ''' return role in get_roles(username, **kwargs) def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxos` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' nxos.cmd sendline 'show ver' salt '*' nxos.cmd show_run salt '*' nxos.cmd check_password username=admin password='$5$lkjsdfoi$blahblahblah' encrypted=True ''' for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) local_command = '.'.join(['nxos', command]) log.info('local command: %s', local_command) if local_command not in __salt__: return False return __salt__[local_command](*args, **kwargs) def find(pattern, **kwargs): ''' Find all instances where the pattern is in the running configuration. .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' matcher = re.compile(pattern, re.MULTILINE) return matcher.findall(show_run(**kwargs)) def get_roles(username, **kwargs): ''' Get roles assigned to a username. .. code-block: bash salt '*' nxos.cmd get_roles username=admin ''' user = get_user(username) if not user: return [] command = 'show user-account {0}'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE) if roles: roles = roles.group(1).strip().split(' ') else: roles = [] return roles def get_user(username, **kwargs): ''' Get username line from switch. .. code-block: bash salt '*' nxos.cmd get_user username=admin ''' command = 'show run | include "^username {0} password 5 "'.format(username) info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) return DEVICE_DETAILS['grains_cache'] def grains_refresh(**kwargs): ''' Refresh the grains for the NX-OS device. .. code-block: bash salt '*' nxos.cmd grains_refresh ''' DEVICE_DETAILS['grains_cache'] = {} return grains(**kwargs) def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitray commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show_ascii``. NOTE: method is ignored for SSH proxy minion. All data is returned unstructured. .. code-block: bash salt '*' nxos.cmd sendline 'show run | include "^username admin password"' ''' smethods = ['cli_show_ascii', 'cli_show', 'cli_conf'] if method not in smethods: msg = """ INPUT ERROR: Second argument 'method' must be one of {0} Value passed: {1} Hint: White space separated commands should be wrapped by double quotes """.format(smethods, method) return msg if salt.utils.platform.is_proxy(): return __proxy__['nxos.sendline'](command, method, **kwargs) else: return _nxapi_request(command, method, **kwargs) def show(commands, raw_text=True, **kwargs): ''' Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. NOTE: raw_text option is ignored for SSH proxy minion. Data is returned unstructured. CLI Example: .. code-block:: bash salt-call --local nxos.show 'show version' salt '*' nxos.show 'show bgp sessions ; show processes' raw_text=False salt 'regular-minion' nxos.show 'show interfaces' host=sw01.example.com username=test password=test ''' if not isinstance(raw_text, bool): msg = """ INPUT ERROR: Second argument 'raw_text' must be either True or False Value passed: {0} Hint: White space separated show commands should be wrapped by double quotes """.format(raw_text) return msg if raw_text: method = 'cli_show_ascii' else: method = 'cli_show' response_list = sendline(commands, method, **kwargs) if isinstance(response_list, list): ret = [response for response in response_list if response] if not ret: ret = [''] return ret else: return response_list def show_ver(**kwargs): ''' Shortcut to run `show version` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_ver ''' command = 'show version' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def show_run(**kwargs): ''' Shortcut to run `show running-config` on the NX-OS device. .. code-block:: bash salt '*' nxos.cmd show_run ''' command = 'show running-config' info = '' info = show(command, **kwargs) if isinstance(info, list): info = info[0] return info def system_info(**kwargs): ''' Return system information for grains of the minion. .. code-block:: bash salt '*' nxos.system_info ''' return salt.utils.nxos.system_info(show_ver(**kwargs))['nxos'] # ----------------------------------------------------------------------------- # Device Get Functions # ----------------------------------------------------------------------------- def add_config(lines, **kwargs): ''' Add one or more config lines to the NX-OS device running config. lines Configuration lines to add no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd add_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config added per command, lines should be a list. ''' return config(lines, **kwargs) def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly to the running-config. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the switch in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the context_dict. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False CLI Example: .. code-block:: bash salt '*' nxos.config commands="['spanning-tree mode mstp']" salt '*' nxos.config config_file=salt://config.txt salt '*' nxos.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" ''' initial_config = show('show running-config', **kwargs) if isinstance(initial_config, list): initial_config = initial_config[0] if config_file: file_str = __salt__['cp.get_file_str'](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError('Source file {} not found'.format(config_file)) elif commands: if isinstance(commands, (six.string_types, six.text_type)): commands = [commands] file_str = '\n'.join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__['file.apply_template_on_contents'](file_str, template_engine, context, defaults, saltenv) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] config_result = _parse_config_result(_configure_device(commands, **kwargs)) current_config = show('show running-config', **kwargs) if isinstance(current_config, list): current_config = current_config[0] diff = difflib.unified_diff(initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:]) clean_diff = ''.join([x.replace('\r', '') for x in diff]) head = 'COMMAND_LIST: ' cc = config_result[0] cr = config_result[1] return head + cc + '\n' + cr + '\n' + clean_diff def _parse_config_result(data): command_list = ' ; '.join([x.strip() for x in data[0]]) config_result = data[1] if isinstance(config_result, list): result = '' if isinstance(config_result[0], dict): for key in config_result[0]: result += config_result[0][key] config_result = result else: config_result = config_result[0] return [command_list, config_result] def delete_config(lines, **kwargs): ''' Delete one or more config lines to the switch running config. lines Configuration lines to remove. no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator' .. note:: For more than one config deleted per command, lines should be a list. ''' if not isinstance(lines, list): lines = [lines] for i, _ in enumerate(lines): lines[i] = 'no ' + lines[i] result = None try: result = config(lines, **kwargs) except CommandExecutionError as e: # Some commands will generate error code 400 if they do not exist # and we try to remove them. These can be ignored. if ast.literal_eval(e.message)['code'] != '400': raise return result def remove_user(username, **kwargs): ''' Remove user from switch. username Username to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd remove_user username=daniel ''' user_line = 'no username {0}'.format(username) return config(user_line, **kwargs) def replace(old_value, new_value, full_match=False, **kwargs): ''' Replace string or full line matches in switch's running config. If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' nxos.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old'], **kwargs) add_config(lines['new'], **kwargs) return lines def save_running_config(**kwargs): ''' Save the running configuration to startup configuration. .. code-block:: bash salt '*' nxos.save_running_config ''' return config(COPY_RS, **kwargs) def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configure crypt_salt setting Default: None alogrithm Encryption algorithm Default: sha256 no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_password admin TestPass salt '*' nxos.cmd set_password admin \\ password='$5$2fWwO2vK$s7.Hr3YltMNHuhywQQ3nfOd.gAPHgs3SOBYYdGT3E.A' \\ encrypted=True ''' password_line = get_user(username, **kwargs) if encrypted is False: if crypt_salt is None: # NXOS does not like non alphanumeric characters. Using the random module from pycrypto # can lead to having non alphanumeric characters in the salt for the hashed password. crypt_salt = secure_password(8, use_random=False) hashed_pass = gen_hash(crypt_salt=crypt_salt, password=password, algorithm=algorithm) else: hashed_pass = password password_line = 'username {0} password 5 {1}'.format(username, hashed_pass) if role is not None: password_line += ' role {0}'.format(role) return config(password_line, **kwargs) def set_role(username, role, **kwargs): ''' Assign role to username. username Username for role configuration role Configure role for username no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd set_role username=daniel role=vdc-admin. ''' role_line = 'username {0} role {1}'.format(username, role) return config(role_line, **kwargs) def unset_role(username, role, **kwargs): ''' Remove role from username. username Username for role removal role Role to remove no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. Default: False .. code-block:: bash salt '*' nxos.cmd unset_role username=daniel role=vdc-admin ''' role_line = 'no username {0} role {1}'.format(username, role) return config(role_line, **kwargs) # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxapi_config(commands, **kwargs) def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs): ''' Helper function to send configuration commands using NX-API. ''' api_kwargs = __salt__['config.get']('nxos', {}) api_kwargs.update(**kwargs) if not isinstance(commands, list): commands = [commands] try: ret = _nxapi_request(commands, **kwargs) if api_kwargs.get('no_save_config'): pass else: _nxapi_request(COPY_RS, **kwargs) for each in ret: if 'Failure' in each: log.error(each) except CommandExecutionError as e: log.error(e) return [commands, repr(e)] return [commands, ret]
saltstack/salt
salt/utils/gzip_util.py
compress
python
def compress(data, compresslevel=9): ''' Returns the data compressed at gzip level compression. ''' buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: if six.PY3 and not isinstance(data, bytes): data = data.encode(__salt_system_encoding__) ogz.write(data) compressed = buf.getvalue() return compressed
Returns the data compressed at gzip level compression.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gzip_util.py#L54-L64
[ "def open_fileobj(fileobj, mode='rb', compresslevel=9):\n if hasattr(gzip.GzipFile, '__enter__'):\n return gzip.GzipFile(\n filename='', mode=mode, fileobj=fileobj,\n compresslevel=compresslevel\n )\n return GzipFile(\n filename='', mode=mode, fileobj=fileobj, compresslevel=compresslevel\n )\n" ]
# -*- coding: utf-8 -*- ''' salt.utils.gzip ~~~~~~~~~~~~~~~ Helper module for handling gzip consistently between 2.7+ and 2.6- ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import gzip # Import Salt libs import salt.utils.files # Import 3rd-party libs from salt.ext import six from salt.ext.six import BytesIO class GzipFile(gzip.GzipFile): def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): gzip.GzipFile.__init__(self, filename, mode, compresslevel, fileobj) ### Context manager (stolen from Python 2.7)### def __enter__(self): """Context management protocol. Returns self.""" return self def __exit__(self, *args): """Context management protocol. Calls close()""" self.close() def open(filename, mode="rb", compresslevel=9): if hasattr(gzip.GzipFile, '__enter__'): return gzip.open(filename, mode, compresslevel) else: return GzipFile(filename, mode, compresslevel) def open_fileobj(fileobj, mode='rb', compresslevel=9): if hasattr(gzip.GzipFile, '__enter__'): return gzip.GzipFile( filename='', mode=mode, fileobj=fileobj, compresslevel=compresslevel ) return GzipFile( filename='', mode=mode, fileobj=fileobj, compresslevel=compresslevel ) def uncompress(data): buf = BytesIO(data) with open_fileobj(buf, 'rb') as igz: unc = igz.read() return unc def compress_file(fh_, compresslevel=9, chunk_size=1048576): ''' Generator that reads chunk_size bytes at a time from a file/filehandle and yields the compressed result of each read. .. note:: Each chunk is compressed separately. They cannot be stitched together to form a compressed file. This function is designed to break up a file into compressed chunks for transport and decompression/reassembly on a remote host. ''' try: bytes_read = int(chunk_size) if bytes_read != chunk_size: raise ValueError except ValueError: raise ValueError('chunk_size must be an integer') try: while bytes_read == chunk_size: buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: try: bytes_read = ogz.write(fh_.read(chunk_size)) except AttributeError: # Open the file and re-attempt the read fh_ = salt.utils.files.fopen(fh_, 'rb') bytes_read = ogz.write(fh_.read(chunk_size)) yield buf.getvalue() finally: try: fh_.close() except AttributeError: pass
saltstack/salt
salt/utils/gzip_util.py
compress_file
python
def compress_file(fh_, compresslevel=9, chunk_size=1048576): ''' Generator that reads chunk_size bytes at a time from a file/filehandle and yields the compressed result of each read. .. note:: Each chunk is compressed separately. They cannot be stitched together to form a compressed file. This function is designed to break up a file into compressed chunks for transport and decompression/reassembly on a remote host. ''' try: bytes_read = int(chunk_size) if bytes_read != chunk_size: raise ValueError except ValueError: raise ValueError('chunk_size must be an integer') try: while bytes_read == chunk_size: buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: try: bytes_read = ogz.write(fh_.read(chunk_size)) except AttributeError: # Open the file and re-attempt the read fh_ = salt.utils.files.fopen(fh_, 'rb') bytes_read = ogz.write(fh_.read(chunk_size)) yield buf.getvalue() finally: try: fh_.close() except AttributeError: pass
Generator that reads chunk_size bytes at a time from a file/filehandle and yields the compressed result of each read. .. note:: Each chunk is compressed separately. They cannot be stitched together to form a compressed file. This function is designed to break up a file into compressed chunks for transport and decompression/reassembly on a remote host.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gzip_util.py#L74-L106
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def open_fileobj(fileobj, mode='rb', compresslevel=9):\n if hasattr(gzip.GzipFile, '__enter__'):\n return gzip.GzipFile(\n filename='', mode=mode, fileobj=fileobj,\n compresslevel=compresslevel\n )\n return GzipFile(\n filename='', mode=mode, fileobj=fileobj, compresslevel=compresslevel\n )\n" ]
# -*- coding: utf-8 -*- ''' salt.utils.gzip ~~~~~~~~~~~~~~~ Helper module for handling gzip consistently between 2.7+ and 2.6- ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import gzip # Import Salt libs import salt.utils.files # Import 3rd-party libs from salt.ext import six from salt.ext.six import BytesIO class GzipFile(gzip.GzipFile): def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): gzip.GzipFile.__init__(self, filename, mode, compresslevel, fileobj) ### Context manager (stolen from Python 2.7)### def __enter__(self): """Context management protocol. Returns self.""" return self def __exit__(self, *args): """Context management protocol. Calls close()""" self.close() def open(filename, mode="rb", compresslevel=9): if hasattr(gzip.GzipFile, '__enter__'): return gzip.open(filename, mode, compresslevel) else: return GzipFile(filename, mode, compresslevel) def open_fileobj(fileobj, mode='rb', compresslevel=9): if hasattr(gzip.GzipFile, '__enter__'): return gzip.GzipFile( filename='', mode=mode, fileobj=fileobj, compresslevel=compresslevel ) return GzipFile( filename='', mode=mode, fileobj=fileobj, compresslevel=compresslevel ) def compress(data, compresslevel=9): ''' Returns the data compressed at gzip level compression. ''' buf = BytesIO() with open_fileobj(buf, 'wb', compresslevel) as ogz: if six.PY3 and not isinstance(data, bytes): data = data.encode(__salt_system_encoding__) ogz.write(data) compressed = buf.getvalue() return compressed def uncompress(data): buf = BytesIO(data) with open_fileobj(buf, 'rb') as igz: unc = igz.read() return unc
saltstack/salt
salt/modules/systemd_service.py
_root
python
def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path
Relocate an absolute path to a new root directory.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L73-L80
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) return ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret def _systemctl_status(name): ''' Helper function which leverages __context__ to keep from running 'systemctl status' more than once. ''' contextkey = 'systemd._systemctl_status.%s' % name if contextkey in __context__: return __context__[contextkey] __context__[contextkey] = __salt__['cmd.run_all']( _systemctl_cmd('status', name), python_shell=False, redirect_stderr=True, ignore_retcode=True ) return __context__[contextkey] def _sysv_enabled(name, root): ''' A System-V style service is assumed disabled if the "startup" symlink (starts with "S") to its script is found in /etc/init.d in the current runlevel. ''' # Find exact match (disambiguate matches like "S01anacron" for cron) rc = _root('/etc/rc{}.d/S*{}'.format(_runlevel(), name), root) for match in glob.glob(rc): if re.match(r'S\d{,2}%s' % name, os.path.basename(match)): return True return False def _untracked_custom_unit_found(name, root=None): ''' If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False. ''' system = _root('/etc/systemd/system', root) unit_path = os.path.join(system, _canonical_unit_name(name)) return os.access(unit_path, os.R_OK) and not _check_available(name) def _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status def systemctl_reload(): ''' .. versionadded:: 0.15.0 Reloads systemctl, an action needed whenever unit files are updated. CLI Example: .. code-block:: bash salt '*' service.systemctl_reload ''' out = __salt__['cmd.run_all']( _systemctl_cmd('--system daemon-reload'), python_shell=False, redirect_stderr=True) if out['retcode'] != 0: raise CommandExecutionError( 'Problem performing systemctl daemon-reload: %s' % out['stdout'] ) _clear_context() return True def get_running(): ''' Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running ''' ret = set() # Get running systemd units out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager'), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: comps = line.strip().split() fullname = comps[0] if len(comps) > 3: active_state = comps[3] except ValueError as exc: log.error(exc) continue else: if active_state != 'running': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) return sorted(ret) def get_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled here because it's # not present until systemd 216. out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager list-unit-files', root=root), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: fullname, unit_state = line.strip().split(None, 1) except ValueError: continue else: if unit_state != 'enabled': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled here because it's # not present until systemd 216. out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager list-unit-files', root=root), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: fullname, unit_state = line.strip().split(None, 1) except ValueError: continue else: if unit_state != 'disabled': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) def get_static(root=None): ''' .. versionadded:: 2015.8.5 Return a list of all static services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_static ''' ret = set() # Get static systemd units. Can't use --state=static here because it's # not present until systemd 216. out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager list-unit-files', root=root), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: fullname, unit_state = line.strip().split(None, 1) except ValueError: continue else: if unit_state != 'static': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) # sysvinit services cannot be static return sorted(ret) def get_all(root=None): ''' Return a list of all available services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = _get_systemd_services(root) ret.update(set(_get_sysv_services(root, systemd_services=ret))) return sorted(ret) def available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def unmask_(name, runtime=False, root=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Unmask the specified service with systemd runtime : False Set to ``True`` to unmask this service only until the next reboot .. versionadded:: 2017.7.0 In previous versions, this function would remove whichever mask was identified by running ``systemctl is-enabled`` on the service. However, since it is possible to both have both indefinite and runtime masks on a service simultaneously, this function now removes a runtime mask only when this argument is set to ``True``, and otherwise removes an indefinite mask. root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.unmask foo salt '*' service.unmask foo runtime=True ''' _check_for_unit_changes(name) if not masked(name, runtime, root=root): log.debug('Service \'%s\' is not %smasked', name, 'runtime-' if runtime else '') return True cmd = 'unmask --runtime' if runtime else 'unmask' out = __salt__['cmd.run_all']( _systemctl_cmd(cmd, name, systemd_scope=True, root=root), python_shell=False, redirect_stderr=True) if out['retcode'] != 0: raise CommandExecutionError('Failed to unmask service \'%s\'' % name) return True def mask(name, runtime=False, root=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Mask the specified service with systemd runtime : False Set to ``True`` to mask this service only until the next reboot .. versionadded:: 2015.8.5 root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.mask foo salt '*' service.mask foo runtime=True ''' _check_for_unit_changes(name) cmd = 'mask --runtime' if runtime else 'mask' out = __salt__['cmd.run_all']( _systemctl_cmd(cmd, name, systemd_scope=True, root=root), python_shell=False, redirect_stderr=True) if out['retcode'] != 0: raise CommandExecutionError( 'Failed to mask service \'%s\'' % name, info=out['stdout'] ) return True def masked(name, runtime=False, root=None): ''' .. versionadded:: 2015.8.0 .. versionchanged:: 2015.8.5 The return data for this function has changed. If the service is masked, the return value will now be the output of the ``systemctl is-enabled`` command (so that a persistent mask can be distinguished from a runtime mask). If the service is not masked, then ``False`` will be returned. .. versionchanged:: 2017.7.0 This function now returns a boolean telling the user whether a mask specified by the new ``runtime`` argument is set. If ``runtime`` is ``False``, this function will return ``True`` if an indefinite mask is set for the named service (otherwise ``False`` will be returned). If ``runtime`` is ``False``, this function will return ``True`` if a runtime mask is set, otherwise ``False``. Check whether or not a service is masked runtime : False Set to ``True`` to check for a runtime mask .. versionadded:: 2017.7.0 In previous versions, this function would simply return the output of ``systemctl is-enabled`` when the service was found to be masked. However, since it is possible to both have both indefinite and runtime masks on a service simultaneously, this function now only checks for runtime masks if this argument is set to ``True``. Otherwise, it will check for an indefinite mask. root Enable/disable/mask unit files in the specified root directory CLI Examples: .. code-block:: bash salt '*' service.masked foo salt '*' service.masked foo runtime=True ''' _check_for_unit_changes(name) root_dir = _root('/run' if runtime else '/etc', root) link_path = os.path.join(root_dir, 'systemd', 'system', _canonical_unit_name(name)) try: return os.readlink(link_path) == '/dev/null' except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Path %s does not exist. This is normal if service \'%s\' is ' 'not masked or does not exist.', link_path, name ) elif exc.errno == errno.EINVAL: log.error( 'Failed to check mask status for service %s. Path %s is a ' 'file, not a symlink. This could be caused by changes in ' 'systemd and is probably a bug in Salt. Please report this ' 'to the developers.', name, link_path ) return False def start(name, no_block=False, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Start the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True def stop(name, no_block=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Stop the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' _check_for_unit_changes(name) # Using cmd.run_all instead of cmd.retcode here to make unit tests easier return __salt__['cmd.run_all']( _systemctl_cmd('stop', name, systemd_scope=True, no_block=no_block), python_shell=False)['retcode'] == 0 def restart(name, no_block=False, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Restart the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to restart the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before restarting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to restart the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before restarting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('restart', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True def reload_(name, no_block=False, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True def force_reload(name, no_block=True, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. versionadded:: 0.12.0 Force-reload the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. def status(name, sig=None): # pylint: disable=unused-argument ''' Return the status for a service via systemd. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Not implemented Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: _check_for_unit_changes(service) results[service] = __salt__['cmd.retcode']( _systemctl_cmd('is-active', service), python_shell=False, ignore_retcode=True) == 0 if contains_globbing: return results return results[name] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. def enable(name, no_block=False, unmask=False, unmask_runtime=False, root=None, **kwargs): # pylint: disable=unused-argument ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Enable the named service to start when the system boots no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to enable the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before enabling. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to enable the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before enabling. This behavior is no longer the default. root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime, root) if name in _get_sysv_services(root): cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) service_exec = _get_service_exec() if service_exec.endswith('/update-rc.d'): cmd.extend([service_exec, '-f', name, 'defaults', '99']) elif service_exec.endswith('/chkconfig'): cmd.extend([service_exec, name, 'on']) return __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=True) == 0 ret = __salt__['cmd.run_all']( _systemctl_cmd('enable', name, systemd_scope=True, no_block=no_block, root=root), python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Disable the named service to not start when the system boots no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' _check_for_unit_changes(name) if name in _get_sysv_services(root): cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) service_exec = _get_service_exec() if service_exec.endswith('/update-rc.d'): cmd.extend([service_exec, '-f', name, 'remove']) elif service_exec.endswith('/chkconfig'): cmd.extend([service_exec, name, 'off']) return __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=True) == 0 # Using cmd.run_all instead of cmd.retcode here to make unit tests easier return __salt__['cmd.run_all']( _systemctl_cmd('disable', name, systemd_scope=True, no_block=no_block, root=root), python_shell=False, ignore_retcode=True)['retcode'] == 0 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. def enabled(name, root=None, **kwargs): # pylint: disable=unused-argument ''' Return if the named service is enabled to start on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # Try 'systemctl is-enabled' first, then look for a symlink created by # systemctl (older systemd releases did not support using is-enabled to # check templated services), and lastly check for a sysvinit service. if __salt__['cmd.retcode'](_systemctl_cmd('is-enabled', name, root=root), python_shell=False, ignore_retcode=True) == 0: return True elif '@' in name: # On older systemd releases, templated services could not be checked # with ``systemctl is-enabled``. As a fallback, look for the symlinks # created by systemctl when enabling templated services. local_config_path = _root(LOCAL_CONFIG_PATH, '/') cmd = ['find', local_config_path, '-name', name, '-type', 'l', '-print', '-quit'] # If the find command returns any matches, there will be output and the # string will be non-empty. if bool(__salt__['cmd.run'](cmd, python_shell=False)): return True elif name in _get_sysv_services(root): return _sysv_enabled(name, root) return False def disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) def show(name, root=None): ''' .. versionadded:: 2014.7.0 Show properties of one or more units/jobs or the manager root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.show <service name> ''' ret = {} out = __salt__['cmd.run'](_systemctl_cmd('show', name, root=root), python_shell=False) for line in salt.utils.itertools.split(out, '\n'): comps = line.split('=') name = comps[0] value = '='.join(comps[1:]) if value.startswith('{'): value = value.replace('{', '').replace('}', '') ret[name] = {} for item in value.split(' ; '): comps = item.split('=') ret[name][comps[0].strip()] = comps[1].strip() elif name in ('Before', 'After', 'Wants'): ret[name] = value.split() else: ret[name] = value return ret def execs(root=None): ''' .. versionadded:: 2014.7.0 Return a list of all files specified as ``ExecStart`` for all services. root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.execs ''' ret = {} for service in get_all(root=root): data = show(service, root=root) if 'ExecStart' not in data: continue ret[service] = data['ExecStart']['path'] return ret
saltstack/salt
salt/modules/systemd_service.py
_canonical_unit_name
python
def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name
Build a canonical unit name treating unit names without one of the valid suffixes as a service.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L83-L92
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) return ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret def _systemctl_status(name): ''' Helper function which leverages __context__ to keep from running 'systemctl status' more than once. ''' contextkey = 'systemd._systemctl_status.%s' % name if contextkey in __context__: return __context__[contextkey] __context__[contextkey] = __salt__['cmd.run_all']( _systemctl_cmd('status', name), python_shell=False, redirect_stderr=True, ignore_retcode=True ) return __context__[contextkey] def _sysv_enabled(name, root): ''' A System-V style service is assumed disabled if the "startup" symlink (starts with "S") to its script is found in /etc/init.d in the current runlevel. ''' # Find exact match (disambiguate matches like "S01anacron" for cron) rc = _root('/etc/rc{}.d/S*{}'.format(_runlevel(), name), root) for match in glob.glob(rc): if re.match(r'S\d{,2}%s' % name, os.path.basename(match)): return True return False def _untracked_custom_unit_found(name, root=None): ''' If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False. ''' system = _root('/etc/systemd/system', root) unit_path = os.path.join(system, _canonical_unit_name(name)) return os.access(unit_path, os.R_OK) and not _check_available(name) def _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status def systemctl_reload(): ''' .. versionadded:: 0.15.0 Reloads systemctl, an action needed whenever unit files are updated. CLI Example: .. code-block:: bash salt '*' service.systemctl_reload ''' out = __salt__['cmd.run_all']( _systemctl_cmd('--system daemon-reload'), python_shell=False, redirect_stderr=True) if out['retcode'] != 0: raise CommandExecutionError( 'Problem performing systemctl daemon-reload: %s' % out['stdout'] ) _clear_context() return True def get_running(): ''' Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running ''' ret = set() # Get running systemd units out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager'), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: comps = line.strip().split() fullname = comps[0] if len(comps) > 3: active_state = comps[3] except ValueError as exc: log.error(exc) continue else: if active_state != 'running': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) return sorted(ret) def get_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled here because it's # not present until systemd 216. out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager list-unit-files', root=root), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: fullname, unit_state = line.strip().split(None, 1) except ValueError: continue else: if unit_state != 'enabled': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled here because it's # not present until systemd 216. out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager list-unit-files', root=root), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: fullname, unit_state = line.strip().split(None, 1) except ValueError: continue else: if unit_state != 'disabled': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) def get_static(root=None): ''' .. versionadded:: 2015.8.5 Return a list of all static services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_static ''' ret = set() # Get static systemd units. Can't use --state=static here because it's # not present until systemd 216. out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pager list-unit-files', root=root), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, '\n'): try: fullname, unit_state = line.strip().split(None, 1) except ValueError: continue else: if unit_state != 'static': continue try: unit_name, unit_type = fullname.rsplit('.', 1) except ValueError: continue if unit_type in VALID_UNIT_TYPES: ret.add(unit_name if unit_type == 'service' else fullname) # sysvinit services cannot be static return sorted(ret) def get_all(root=None): ''' Return a list of all available services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = _get_systemd_services(root) ret.update(set(_get_sysv_services(root, systemd_services=ret))) return sorted(ret) def available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def unmask_(name, runtime=False, root=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Unmask the specified service with systemd runtime : False Set to ``True`` to unmask this service only until the next reboot .. versionadded:: 2017.7.0 In previous versions, this function would remove whichever mask was identified by running ``systemctl is-enabled`` on the service. However, since it is possible to both have both indefinite and runtime masks on a service simultaneously, this function now removes a runtime mask only when this argument is set to ``True``, and otherwise removes an indefinite mask. root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.unmask foo salt '*' service.unmask foo runtime=True ''' _check_for_unit_changes(name) if not masked(name, runtime, root=root): log.debug('Service \'%s\' is not %smasked', name, 'runtime-' if runtime else '') return True cmd = 'unmask --runtime' if runtime else 'unmask' out = __salt__['cmd.run_all']( _systemctl_cmd(cmd, name, systemd_scope=True, root=root), python_shell=False, redirect_stderr=True) if out['retcode'] != 0: raise CommandExecutionError('Failed to unmask service \'%s\'' % name) return True def mask(name, runtime=False, root=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Mask the specified service with systemd runtime : False Set to ``True`` to mask this service only until the next reboot .. versionadded:: 2015.8.5 root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.mask foo salt '*' service.mask foo runtime=True ''' _check_for_unit_changes(name) cmd = 'mask --runtime' if runtime else 'mask' out = __salt__['cmd.run_all']( _systemctl_cmd(cmd, name, systemd_scope=True, root=root), python_shell=False, redirect_stderr=True) if out['retcode'] != 0: raise CommandExecutionError( 'Failed to mask service \'%s\'' % name, info=out['stdout'] ) return True def masked(name, runtime=False, root=None): ''' .. versionadded:: 2015.8.0 .. versionchanged:: 2015.8.5 The return data for this function has changed. If the service is masked, the return value will now be the output of the ``systemctl is-enabled`` command (so that a persistent mask can be distinguished from a runtime mask). If the service is not masked, then ``False`` will be returned. .. versionchanged:: 2017.7.0 This function now returns a boolean telling the user whether a mask specified by the new ``runtime`` argument is set. If ``runtime`` is ``False``, this function will return ``True`` if an indefinite mask is set for the named service (otherwise ``False`` will be returned). If ``runtime`` is ``False``, this function will return ``True`` if a runtime mask is set, otherwise ``False``. Check whether or not a service is masked runtime : False Set to ``True`` to check for a runtime mask .. versionadded:: 2017.7.0 In previous versions, this function would simply return the output of ``systemctl is-enabled`` when the service was found to be masked. However, since it is possible to both have both indefinite and runtime masks on a service simultaneously, this function now only checks for runtime masks if this argument is set to ``True``. Otherwise, it will check for an indefinite mask. root Enable/disable/mask unit files in the specified root directory CLI Examples: .. code-block:: bash salt '*' service.masked foo salt '*' service.masked foo runtime=True ''' _check_for_unit_changes(name) root_dir = _root('/run' if runtime else '/etc', root) link_path = os.path.join(root_dir, 'systemd', 'system', _canonical_unit_name(name)) try: return os.readlink(link_path) == '/dev/null' except OSError as exc: if exc.errno == errno.ENOENT: log.trace( 'Path %s does not exist. This is normal if service \'%s\' is ' 'not masked or does not exist.', link_path, name ) elif exc.errno == errno.EINVAL: log.error( 'Failed to check mask status for service %s. Path %s is a ' 'file, not a symlink. This could be caused by changes in ' 'systemd and is probably a bug in Salt. Please report this ' 'to the developers.', name, link_path ) return False def start(name, no_block=False, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Start the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True def stop(name, no_block=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Stop the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' _check_for_unit_changes(name) # Using cmd.run_all instead of cmd.retcode here to make unit tests easier return __salt__['cmd.run_all']( _systemctl_cmd('stop', name, systemd_scope=True, no_block=no_block), python_shell=False)['retcode'] == 0 def restart(name, no_block=False, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Restart the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to restart the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before restarting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to restart the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before restarting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('restart', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True def reload_(name, no_block=False, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True def force_reload(name, no_block=True, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html .. versionadded:: 0.12.0 Force-reload the specified service with systemd no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', name, systemd_scope=True, no_block=no_block), python_shell=False) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. def status(name, sig=None): # pylint: disable=unused-argument ''' Return the status for a service via systemd. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Not implemented Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: _check_for_unit_changes(service) results[service] = __salt__['cmd.retcode']( _systemctl_cmd('is-active', service), python_shell=False, ignore_retcode=True) == 0 if contains_globbing: return results return results[name] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. def enable(name, no_block=False, unmask=False, unmask_runtime=False, root=None, **kwargs): # pylint: disable=unused-argument ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Enable the named service to start when the system boots no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to enable the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before enabling. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to enable the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before enabling. This behavior is no longer the default. root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime, root) if name in _get_sysv_services(root): cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) service_exec = _get_service_exec() if service_exec.endswith('/update-rc.d'): cmd.extend([service_exec, '-f', name, 'defaults', '99']) elif service_exec.endswith('/chkconfig'): cmd.extend([service_exec, name, 'on']) return __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=True) == 0 ret = __salt__['cmd.run_all']( _systemctl_cmd('enable', name, systemd_scope=True, no_block=no_block, root=root), python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: # Instead of returning a bool, raise an exception so that we can # include the error message in the return data. This helps give more # information to the user in instances where the service is masked. raise CommandExecutionError(_strip_scope(ret['stderr'])) return True # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is restarted while a service is being modified. If desired, usage of `systemd-run(1)`_ can be suppressed by setting a :mod:`config option <salt.modules.config.get>` called ``systemd.scope``, with a value of ``False`` (no quotes). .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html Disable the named service to not start when the system boots no_block : False Set to ``True`` to start the service using ``--no-block``. .. versionadded:: 2017.7.0 root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' _check_for_unit_changes(name) if name in _get_sysv_services(root): cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) service_exec = _get_service_exec() if service_exec.endswith('/update-rc.d'): cmd.extend([service_exec, '-f', name, 'remove']) elif service_exec.endswith('/chkconfig'): cmd.extend([service_exec, name, 'off']) return __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=True) == 0 # Using cmd.run_all instead of cmd.retcode here to make unit tests easier return __salt__['cmd.run_all']( _systemctl_cmd('disable', name, systemd_scope=True, no_block=no_block, root=root), python_shell=False, ignore_retcode=True)['retcode'] == 0 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. def enabled(name, root=None, **kwargs): # pylint: disable=unused-argument ''' Return if the named service is enabled to start on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # Try 'systemctl is-enabled' first, then look for a symlink created by # systemctl (older systemd releases did not support using is-enabled to # check templated services), and lastly check for a sysvinit service. if __salt__['cmd.retcode'](_systemctl_cmd('is-enabled', name, root=root), python_shell=False, ignore_retcode=True) == 0: return True elif '@' in name: # On older systemd releases, templated services could not be checked # with ``systemctl is-enabled``. As a fallback, look for the symlinks # created by systemctl when enabling templated services. local_config_path = _root(LOCAL_CONFIG_PATH, '/') cmd = ['find', local_config_path, '-name', name, '-type', 'l', '-print', '-quit'] # If the find command returns any matches, there will be output and the # string will be non-empty. if bool(__salt__['cmd.run'](cmd, python_shell=False)): return True elif name in _get_sysv_services(root): return _sysv_enabled(name, root) return False def disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) def show(name, root=None): ''' .. versionadded:: 2014.7.0 Show properties of one or more units/jobs or the manager root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.show <service name> ''' ret = {} out = __salt__['cmd.run'](_systemctl_cmd('show', name, root=root), python_shell=False) for line in salt.utils.itertools.split(out, '\n'): comps = line.split('=') name = comps[0] value = '='.join(comps[1:]) if value.startswith('{'): value = value.replace('{', '').replace('}', '') ret[name] = {} for item in value.split(' ; '): comps = item.split('=') ret[name][comps[0].strip()] = comps[1].strip() elif name in ('Before', 'After', 'Wants'): ret[name] = value.split() else: ret[name] = value return ret def execs(root=None): ''' .. versionadded:: 2014.7.0 Return a list of all files specified as ``ExecStart`` for all services. root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.execs ''' ret = {} for service in get_all(root=root): data = show(service, root=root) if 'ExecStart' not in data: continue ret[service] = data['ExecStart']['path'] return ret