PageRenderTime 20ms CodeModel.GetById 11ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/ajanthanm/ansible
Python | 78 lines | 56 code | 5 blank | 17 comment | 2 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
18from ansible import utils
19import os
20import urllib2
21try:
22    import json
23except ImportError:
24    import simplejson as json
25
26# this can be made configurable, not should not use ansible.cfg
27ANSIBLE_ETCD_URL = 'http://127.0.0.1:4001'
28if os.getenv('ANSIBLE_ETCD_URL') is not None:
29    ANSIBLE_ETCD_URL = os.environ['ANSIBLE_ETCD_URL']
30
31class etcd():
32    def __init__(self, url=ANSIBLE_ETCD_URL):
33        self.url = url
34        self.baseurl = '%s/v1/keys' % (self.url)
35
36    def get(self, key):
37        url = "%s/%s" % (self.baseurl, key)
38
39        data = None
40        value = ""
41        try:
42            r = urllib2.urlopen(url)
43            data = r.read()
44        except:
45            return value
46
47        try:
48            # {"action":"get","key":"/name","value":"Jane Jolie","index":5}
49            item = json.loads(data)
50            if 'value' in item:
51                value = item['value']
52            if 'errorCode' in item:
53                value = "ENOENT"
54        except:
55            raise
56            pass
57
58        return value
59
60class LookupModule(object):
61
62    def __init__(self, basedir=None, **kwargs):
63        self.basedir = basedir
64        self.etcd = etcd()
65
66    def run(self, terms, inject=None, **kwargs):
67
68        terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject)
69
70        if isinstance(terms, basestring):
71            terms = [ terms ]
72
73        ret = []
74        for term in terms:
75            key = term.split()[0]
76            value = self.etcd.get(key)
77            ret.append(value)
78        return ret