def resolve_by_name(func, name, *args): """ Helper to resolve a "name" a'la foo.com to it's ID by using REST api's query support and filtering on name. """ if uuidutils.is_uuid_like(name): return name results = func(criterion={"name": "%s" % name}, *args) length = len(results) if length == 1: return results[0]["id"] elif length == 0: raise exceptions.NotFound("Name %s didn't resolve" % name) else: msg = "Multiple matches found for %s, please use ID instead." % name raise exceptions.NoUniqueMatch(msg)
def find_resourceid_by_name_or_id(resource_client, name_or_id): """Find resource id from its id or name.""" try: # Try to return an uuid return str(uuid.UUID(name_or_id)) except ValueError: # Not an uuid => assume it is resource name pass resources = resource_client.list() candidate_ids = [r['id'] for r in resources if r.get('name') == name_or_id] if not candidate_ids: raise exceptions.ResourceNotFound( 'Could not find resource with name "%s"' % name_or_id) elif len(candidate_ids) > 1: str_ids = ','.join(candidate_ids) raise exceptions.NoUniqueMatch( 'Multiple resources with name "%s": %s' % (name_or_id, str_ids)) return candidate_ids[0]