/lib/ansible/runner/lookup_plugins/etcd.py

https://github.com/ajanthanm/ansible · Python · 78 lines · 47 code · 13 blank · 18 comment · 9 complexity · 32a02f6a79918e12f5fa4387e87faee8 MD5 · raw file

  1. # (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com>
  2. #
  3. # This file is part of Ansible
  4. #
  5. # Ansible is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # Ansible is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  17. from ansible import utils
  18. import os
  19. import urllib2
  20. try:
  21. import json
  22. except ImportError:
  23. import simplejson as json
  24. # this can be made configurable, not should not use ansible.cfg
  25. ANSIBLE_ETCD_URL = 'http://127.0.0.1:4001'
  26. if os.getenv('ANSIBLE_ETCD_URL') is not None:
  27. ANSIBLE_ETCD_URL = os.environ['ANSIBLE_ETCD_URL']
  28. class etcd():
  29. def __init__(self, url=ANSIBLE_ETCD_URL):
  30. self.url = url
  31. self.baseurl = '%s/v1/keys' % (self.url)
  32. def get(self, key):
  33. url = "%s/%s" % (self.baseurl, key)
  34. data = None
  35. value = ""
  36. try:
  37. r = urllib2.urlopen(url)
  38. data = r.read()
  39. except:
  40. return value
  41. try:
  42. # {"action":"get","key":"/name","value":"Jane Jolie","index":5}
  43. item = json.loads(data)
  44. if 'value' in item:
  45. value = item['value']
  46. if 'errorCode' in item:
  47. value = "ENOENT"
  48. except:
  49. raise
  50. pass
  51. return value
  52. class LookupModule(object):
  53. def __init__(self, basedir=None, **kwargs):
  54. self.basedir = basedir
  55. self.etcd = etcd()
  56. def run(self, terms, inject=None, **kwargs):
  57. terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject)
  58. if isinstance(terms, basestring):
  59. terms = [ terms ]
  60. ret = []
  61. for term in terms:
  62. key = term.split()[0]
  63. value = self.etcd.get(key)
  64. ret.append(value)
  65. return ret