We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bad consul_kv token default
Currently the documentation says the token defaults to `None` but the code does not:
https://github.com/ansible/ansible-modules-extras/blob/devel/clustering/consul_kv.py#L244

Note: The current default breaks bootstrapped agent acls.

I can try and send a PR shortly to fix this unless someone else beats me to it!


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `clustering/consul_kv.py`
Content:
```
1 #!/usr/bin/python
2 #
3 # (c) 2015, Steve Gargan <steve.gargan@gmail.com>
4 #
5 # This file is part of Ansible
6 #
7 # Ansible is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Ansible is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
19 
20 DOCUMENTATION = """
21 module: consul_kv
22 short_description: Manipulate entries in the key/value store of a consul cluster.
23 description:
24   - Allows the addition, modification and deletion of key/value entries in a
25     consul cluster via the agent. The entire contents of the record, including
26     the indices, flags and session are returned as 'value'.
27   - If the key represents a prefix then Note that when a value is removed, the existing
28     value if any is returned as part of the results.
29   - "See http://www.consul.io/docs/agent/http.html#kv for more details."
30 requirements:
31   - "python >= 2.6"
32   - python-consul
33   - requests
34 version_added: "2.0"
35 author: "Steve Gargan (@sgargan)"
36 options:
37     state:
38         description:
39           - the action to take with the supplied key and value. If the state is
40             'present', the key contents will be set to the value supplied,
41             'changed' will be set to true only if the value was different to the
42             current contents. The state 'absent' will remove the key/value pair,
43             again 'changed' will be set to true only if the key actually existed
44             prior to the removal. An attempt can be made to obtain or free the
45             lock associated with a key/value pair with the states 'acquire' or
46             'release' respectively. a valid session must be supplied to make the
47             attempt changed will be true if the attempt is successful, false
48             otherwise.
49         required: false
50         choices: ['present', 'absent', 'acquire', 'release']
51         default: present
52     key:
53         description:
54           - the key at which the value should be stored.
55         required: true
56     value:
57         description:
58           - the value should be associated with the given key, required if state
59             is present
60         required: true
61     recurse:
62         description:
63           - if the key represents a prefix, each entry with the prefix can be
64             retrieved by setting this to true.
65         required: false
66         default: false
67     session:
68         description:
69           - the session that should be used to acquire or release a lock
70             associated with a key/value pair
71         required: false
72         default: None
73     token:
74         description:
75           - the token key indentifying an ACL rule set that controls access to
76             the key value pair
77         required: false
78         default: None
79     cas:
80         description:
81           - used when acquiring a lock with a session. If the cas is 0, then
82             Consul will only put the key if it does not already exist. If the
83             cas value is non-zero, then the key is only set if the index matches
84             the ModifyIndex of that key.
85         required: false
86         default: None
87     flags:
88         description:
89           - opaque integer value that can be passed when setting a value.
90         required: false
91         default: None
92     host:
93         description:
94           - host of the consul agent defaults to localhost
95         required: false
96         default: localhost
97     port:
98         description:
99           - the port on which the consul agent is running
100         required: false
101         default: 8500
102     scheme:
103         description:
104           - the protocol scheme on which the consul agent is running
105         required: false
106         default: http
107         version_added: "2.1"
108     validate_certs:
109         description:
110           - whether to verify the tls certificate of the consul agent
111         required: false
112         default: True
113         version_added: "2.1"
114 """
115 
116 
117 EXAMPLES = '''
118 
119   - name: add or update the value associated with a key in the key/value store
120     consul_kv:
121       key: somekey
122       value: somevalue
123 
124   - name: remove a key from the store
125     consul_kv:
126       key: somekey
127       state: absent
128 
129   - name: add a node to an arbitrary group via consul inventory (see consul.ini)
130     consul_kv:
131       key: ansible/groups/dc1/somenode
132       value: 'top_secret'
133 
134   - name: Register a key/value pair with an associated session
135     consul_kv:
136       key: stg/node/server_birthday
137       value: 20160509
138       session: "{{ sessionid }}"
139       state: acquire
140 '''
141 
142 import sys
143 
144 try:
145     import consul
146     from requests.exceptions import ConnectionError
147     python_consul_installed = True
148 except ImportError:
149     python_consul_installed = False
150 
151 from requests.exceptions import ConnectionError
152 
153 def execute(module):
154 
155     state = module.params.get('state')
156 
157     if state == 'acquire' or state == 'release':
158         lock(module, state)
159     if state == 'present':
160         add_value(module)
161     else:
162         remove_value(module)
163 
164 
165 def lock(module, state):
166 
167     consul_api = get_consul_api(module)
168 
169     session = module.params.get('session')
170     key = module.params.get('key')
171     value = module.params.get('value')
172 
173     if not session:
174         module.fail(
175             msg='%s of lock for %s requested but no session supplied' %
176             (state, key))
177 
178     index, existing = consul_api.kv.get(key)
179 
180     changed = not existing or (existing and existing['Value'] != value)
181     if changed and not module.check_mode:
182         if state == 'acquire':
183             changed = consul_api.kv.put(key, value,
184                                         cas=module.params.get('cas'),
185                                         acquire=session,
186                                         flags=module.params.get('flags'))
187         else:
188             changed = consul_api.kv.put(key, value,
189                                         cas=module.params.get('cas'),
190                                         release=session,
191                                         flags=module.params.get('flags'))
192 
193     module.exit_json(changed=changed,
194                      index=index,
195                      key=key)
196 
197 
198 def add_value(module):
199 
200     consul_api = get_consul_api(module)
201 
202     key = module.params.get('key')
203     value = module.params.get('value')
204 
205     index, existing = consul_api.kv.get(key)
206 
207     changed = not existing or (existing and existing['Value'] != value)
208     if changed and not module.check_mode:
209         changed = consul_api.kv.put(key, value,
210                                     cas=module.params.get('cas'),
211                                     flags=module.params.get('flags'))
212 
213     if module.params.get('retrieve'):
214         index, stored = consul_api.kv.get(key)
215 
216     module.exit_json(changed=changed,
217                      index=index,
218                      key=key,
219                      data=stored)
220 
221 
222 def remove_value(module):
223     ''' remove the value associated with the given key. if the recurse parameter
224      is set then any key prefixed with the given key will be removed. '''
225     consul_api = get_consul_api(module)
226 
227     key = module.params.get('key')
228     value = module.params.get('value')
229 
230     index, existing = consul_api.kv.get(
231         key, recurse=module.params.get('recurse'))
232 
233     changed = existing != None
234     if changed and not module.check_mode:
235         consul_api.kv.delete(key, module.params.get('recurse'))
236 
237     module.exit_json(changed=changed,
238                      index=index,
239                      key=key,
240                      data=existing)
241 
242 
243 def get_consul_api(module, token=None):
244     return consul.Consul(host=module.params.get('host'),
245                          port=module.params.get('port'),
246                          scheme=module.params.get('scheme'),
247                          verify=module.params.get('validate_certs'),
248                          token=module.params.get('token'))
249 
250 def test_dependencies(module):
251     if not python_consul_installed:
252         module.fail_json(msg="python-consul required for this module. "\
253               "see http://python-consul.readthedocs.org/en/latest/#installation")
254     
255 def main():
256 
257     argument_spec = dict(
258         cas=dict(required=False),
259         flags=dict(required=False),
260         key=dict(required=True),
261         host=dict(default='localhost'),
262         scheme=dict(required=False, default='http'),
263         validate_certs=dict(required=False, default=True),
264         port=dict(default=8500, type='int'),
265         recurse=dict(required=False, type='bool'),
266         retrieve=dict(required=False, default=True),
267         state=dict(default='present', choices=['present', 'absent', 'acquire', 'release']),
268         token=dict(required=False, default='anonymous', no_log=True),
269         value=dict(required=False),
270         session=dict(required=False)
271     )
272 
273     module = AnsibleModule(argument_spec, supports_check_mode=False)
274 
275     test_dependencies(module)
276         
277     try:
278         execute(module)
279     except ConnectionError as e:
280         module.fail_json(msg='Could not connect to consul agent at %s:%s, error was %s' % (
281                             module.params.get('host'), module.params.get('port'), str(e)))
282     except Exception as e:
283         module.fail_json(msg=str(e))
284 
285 
286 # import module snippets
287 from ansible.module_utils.basic import *
288 if __name__ == '__main__':
289     main()
290
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/clustering/consul_kv.py b/clustering/consul_kv.py
--- a/clustering/consul_kv.py
+++ b/clustering/consul_kv.py
@@ -251,7 +251,7 @@
     if not python_consul_installed:
         module.fail_json(msg="python-consul required for this module. "\
               "see http://python-consul.readthedocs.org/en/latest/#installation")
-    
+
 def main():
 
     argument_spec = dict(
@@ -265,7 +265,7 @@
         recurse=dict(required=False, type='bool'),
         retrieve=dict(required=False, default=True),
         state=dict(default='present', choices=['present', 'absent', 'acquire', 'release']),
-        token=dict(required=False, default='anonymous', no_log=True),
+        token=dict(required=False, no_log=True),
         value=dict(required=False),
         session=dict(required=False)
     )
@@ -273,7 +273,7 @@
     module = AnsibleModule(argument_spec, supports_check_mode=False)
 
     test_dependencies(module)
-        
+
     try:
         execute(module)
     except ConnectionError as e:

{"golden_diff": "diff --git a/clustering/consul_kv.py b/clustering/consul_kv.py\n--- a/clustering/consul_kv.py\n+++ b/clustering/consul_kv.py\n@@ -251,7 +251,7 @@\n     if not python_consul_installed:\n         module.fail_json(msg=\"python-consul required for this module. \"\\\n               \"see http://python-consul.readthedocs.org/en/latest/#installation\")\n-    \n+\n def main():\n \n     argument_spec = dict(\n@@ -265,7 +265,7 @@\n         recurse=dict(required=False, type='bool'),\n         retrieve=dict(required=False, default=True),\n         state=dict(default='present', choices=['present', 'absent', 'acquire', 'release']),\n-        token=dict(required=False, default='anonymous', no_log=True),\n+        token=dict(required=False, no_log=True),\n         value=dict(required=False),\n         session=dict(required=False)\n     )\n@@ -273,7 +273,7 @@\n     module = AnsibleModule(argument_spec, supports_check_mode=False)\n \n     test_dependencies(module)\n-        \n+\n     try:\n         execute(module)\n     except ConnectionError as e:\n", "issue": "Bad consul_kv token default\nCurrently the documentation says the token defaults to `None` but the code does not:\nhttps://github.com/ansible/ansible-modules-extras/blob/devel/clustering/consul_kv.py#L244\n\nNote: The current default breaks bootstrapped agent acls.\n\nI can try and send a PR shortly to fix this unless someone else beats me to it!\n\n", "before_files": [{"content": "#!/usr/bin/python\n#\n# (c) 2015, Steve Gargan <steve.gargan@gmail.com>\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\n\nDOCUMENTATION = \"\"\"\nmodule: consul_kv\nshort_description: Manipulate entries in the key/value store of a consul cluster.\ndescription:\n  - Allows the addition, modification and deletion of key/value entries in a\n    consul cluster via the agent. The entire contents of the record, including\n    the indices, flags and session are returned as 'value'.\n  - If the key represents a prefix then Note that when a value is removed, the existing\n    value if any is returned as part of the results.\n  - \"See http://www.consul.io/docs/agent/http.html#kv for more details.\"\nrequirements:\n  - \"python >= 2.6\"\n  - python-consul\n  - requests\nversion_added: \"2.0\"\nauthor: \"Steve Gargan (@sgargan)\"\noptions:\n    state:\n        description:\n          - the action to take with the supplied key and value. If the state is\n            'present', the key contents will be set to the value supplied,\n            'changed' will be set to true only if the value was different to the\n            current contents. The state 'absent' will remove the key/value pair,\n            again 'changed' will be set to true only if the key actually existed\n            prior to the removal. An attempt can be made to obtain or free the\n            lock associated with a key/value pair with the states 'acquire' or\n            'release' respectively. a valid session must be supplied to make the\n            attempt changed will be true if the attempt is successful, false\n            otherwise.\n        required: false\n        choices: ['present', 'absent', 'acquire', 'release']\n        default: present\n    key:\n        description:\n          - the key at which the value should be stored.\n        required: true\n    value:\n        description:\n          - the value should be associated with the given key, required if state\n            is present\n        required: true\n    recurse:\n        description:\n          - if the key represents a prefix, each entry with the prefix can be\n            retrieved by setting this to true.\n        required: false\n        default: false\n    session:\n        description:\n          - the session that should be used to acquire or release a lock\n            associated with a key/value pair\n        required: false\n        default: None\n    token:\n        description:\n          - the token key indentifying an ACL rule set that controls access to\n            the key value pair\n        required: false\n        default: None\n    cas:\n        description:\n          - used when acquiring a lock with a session. If the cas is 0, then\n            Consul will only put the key if it does not already exist. If the\n            cas value is non-zero, then the key is only set if the index matches\n            the ModifyIndex of that key.\n        required: false\n        default: None\n    flags:\n        description:\n          - opaque integer value that can be passed when setting a value.\n        required: false\n        default: None\n    host:\n        description:\n          - host of the consul agent defaults to localhost\n        required: false\n        default: localhost\n    port:\n        description:\n          - the port on which the consul agent is running\n        required: false\n        default: 8500\n    scheme:\n        description:\n          - the protocol scheme on which the consul agent is running\n        required: false\n        default: http\n        version_added: \"2.1\"\n    validate_certs:\n        description:\n          - whether to verify the tls certificate of the consul agent\n        required: false\n        default: True\n        version_added: \"2.1\"\n\"\"\"\n\n\nEXAMPLES = '''\n\n  - name: add or update the value associated with a key in the key/value store\n    consul_kv:\n      key: somekey\n      value: somevalue\n\n  - name: remove a key from the store\n    consul_kv:\n      key: somekey\n      state: absent\n\n  - name: add a node to an arbitrary group via consul inventory (see consul.ini)\n    consul_kv:\n      key: ansible/groups/dc1/somenode\n      value: 'top_secret'\n\n  - name: Register a key/value pair with an associated session\n    consul_kv:\n      key: stg/node/server_birthday\n      value: 20160509\n      session: \"{{ sessionid }}\"\n      state: acquire\n'''\n\nimport sys\n\ntry:\n    import consul\n    from requests.exceptions import ConnectionError\n    python_consul_installed = True\nexcept ImportError:\n    python_consul_installed = False\n\nfrom requests.exceptions import ConnectionError\n\ndef execute(module):\n\n    state = module.params.get('state')\n\n    if state == 'acquire' or state == 'release':\n        lock(module, state)\n    if state == 'present':\n        add_value(module)\n    else:\n        remove_value(module)\n\n\ndef lock(module, state):\n\n    consul_api = get_consul_api(module)\n\n    session = module.params.get('session')\n    key = module.params.get('key')\n    value = module.params.get('value')\n\n    if not session:\n        module.fail(\n            msg='%s of lock for %s requested but no session supplied' %\n            (state, key))\n\n    index, existing = consul_api.kv.get(key)\n\n    changed = not existing or (existing and existing['Value'] != value)\n    if changed and not module.check_mode:\n        if state == 'acquire':\n            changed = consul_api.kv.put(key, value,\n                                        cas=module.params.get('cas'),\n                                        acquire=session,\n                                        flags=module.params.get('flags'))\n        else:\n            changed = consul_api.kv.put(key, value,\n                                        cas=module.params.get('cas'),\n                                        release=session,\n                                        flags=module.params.get('flags'))\n\n    module.exit_json(changed=changed,\n                     index=index,\n                     key=key)\n\n\ndef add_value(module):\n\n    consul_api = get_consul_api(module)\n\n    key = module.params.get('key')\n    value = module.params.get('value')\n\n    index, existing = consul_api.kv.get(key)\n\n    changed = not existing or (existing and existing['Value'] != value)\n    if changed and not module.check_mode:\n        changed = consul_api.kv.put(key, value,\n                                    cas=module.params.get('cas'),\n                                    flags=module.params.get('flags'))\n\n    if module.params.get('retrieve'):\n        index, stored = consul_api.kv.get(key)\n\n    module.exit_json(changed=changed,\n                     index=index,\n                     key=key,\n                     data=stored)\n\n\ndef remove_value(module):\n    ''' remove the value associated with the given key. if the recurse parameter\n     is set then any key prefixed with the given key will be removed. '''\n    consul_api = get_consul_api(module)\n\n    key = module.params.get('key')\n    value = module.params.get('value')\n\n    index, existing = consul_api.kv.get(\n        key, recurse=module.params.get('recurse'))\n\n    changed = existing != None\n    if changed and not module.check_mode:\n        consul_api.kv.delete(key, module.params.get('recurse'))\n\n    module.exit_json(changed=changed,\n                     index=index,\n                     key=key,\n                     data=existing)\n\n\ndef get_consul_api(module, token=None):\n    return consul.Consul(host=module.params.get('host'),\n                         port=module.params.get('port'),\n                         scheme=module.params.get('scheme'),\n                         verify=module.params.get('validate_certs'),\n                         token=module.params.get('token'))\n\ndef test_dependencies(module):\n    if not python_consul_installed:\n        module.fail_json(msg=\"python-consul required for this module. \"\\\n              \"see http://python-consul.readthedocs.org/en/latest/#installation\")\n    \ndef main():\n\n    argument_spec = dict(\n        cas=dict(required=False),\n        flags=dict(required=False),\n        key=dict(required=True),\n        host=dict(default='localhost'),\n        scheme=dict(required=False, default='http'),\n        validate_certs=dict(required=False, default=True),\n        port=dict(default=8500, type='int'),\n        recurse=dict(required=False, type='bool'),\n        retrieve=dict(required=False, default=True),\n        state=dict(default='present', choices=['present', 'absent', 'acquire', 'release']),\n        token=dict(required=False, default='anonymous', no_log=True),\n        value=dict(required=False),\n        session=dict(required=False)\n    )\n\n    module = AnsibleModule(argument_spec, supports_check_mode=False)\n\n    test_dependencies(module)\n        \n    try:\n        execute(module)\n    except ConnectionError as e:\n        module.fail_json(msg='Could not connect to consul agent at %s:%s, error was %s' % (\n                            module.params.get('host'), module.params.get('port'), str(e)))\n    except Exception as e:\n        module.fail_json(msg=str(e))\n\n\n# import module snippets\nfrom ansible.module_utils.basic import *\nif __name__ == '__main__':\n    main()\n", "path": "clustering/consul_kv.py"}], "after_files": [{"content": "#!/usr/bin/python\n#\n# (c) 2015, Steve Gargan <steve.gargan@gmail.com>\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.\n\nDOCUMENTATION = \"\"\"\nmodule: consul_kv\nshort_description: Manipulate entries in the key/value store of a consul cluster.\ndescription:\n  - Allows the addition, modification and deletion of key/value entries in a\n    consul cluster via the agent. The entire contents of the record, including\n    the indices, flags and session are returned as 'value'.\n  - If the key represents a prefix then Note that when a value is removed, the existing\n    value if any is returned as part of the results.\n  - \"See http://www.consul.io/docs/agent/http.html#kv for more details.\"\nrequirements:\n  - \"python >= 2.6\"\n  - python-consul\n  - requests\nversion_added: \"2.0\"\nauthor: \"Steve Gargan (@sgargan)\"\noptions:\n    state:\n        description:\n          - the action to take with the supplied key and value. If the state is\n            'present', the key contents will be set to the value supplied,\n            'changed' will be set to true only if the value was different to the\n            current contents. The state 'absent' will remove the key/value pair,\n            again 'changed' will be set to true only if the key actually existed\n            prior to the removal. An attempt can be made to obtain or free the\n            lock associated with a key/value pair with the states 'acquire' or\n            'release' respectively. a valid session must be supplied to make the\n            attempt changed will be true if the attempt is successful, false\n            otherwise.\n        required: false\n        choices: ['present', 'absent', 'acquire', 'release']\n        default: present\n    key:\n        description:\n          - the key at which the value should be stored.\n        required: true\n    value:\n        description:\n          - the value should be associated with the given key, required if state\n            is present\n        required: true\n    recurse:\n        description:\n          - if the key represents a prefix, each entry with the prefix can be\n            retrieved by setting this to true.\n        required: false\n        default: false\n    session:\n        description:\n          - the session that should be used to acquire or release a lock\n            associated with a key/value pair\n        required: false\n        default: None\n    token:\n        description:\n          - the token key indentifying an ACL rule set that controls access to\n            the key value pair\n        required: false\n        default: None\n    cas:\n        description:\n          - used when acquiring a lock with a session. If the cas is 0, then\n            Consul will only put the key if it does not already exist. If the\n            cas value is non-zero, then the key is only set if the index matches\n            the ModifyIndex of that key.\n        required: false\n        default: None\n    flags:\n        description:\n          - opaque integer value that can be passed when setting a value.\n        required: false\n        default: None\n    host:\n        description:\n          - host of the consul agent defaults to localhost\n        required: false\n        default: localhost\n    port:\n        description:\n          - the port on which the consul agent is running\n        required: false\n        default: 8500\n    scheme:\n        description:\n          - the protocol scheme on which the consul agent is running\n        required: false\n        default: http\n        version_added: \"2.1\"\n    validate_certs:\n        description:\n          - whether to verify the tls certificate of the consul agent\n        required: false\n        default: True\n        version_added: \"2.1\"\n\"\"\"\n\n\nEXAMPLES = '''\n\n  - name: add or update the value associated with a key in the key/value store\n    consul_kv:\n      key: somekey\n      value: somevalue\n\n  - name: remove a key from the store\n    consul_kv:\n      key: somekey\n      state: absent\n\n  - name: add a node to an arbitrary group via consul inventory (see consul.ini)\n    consul_kv:\n      key: ansible/groups/dc1/somenode\n      value: 'top_secret'\n\n  - name: Register a key/value pair with an associated session\n    consul_kv:\n      key: stg/node/server_birthday\n      value: 20160509\n      session: \"{{ sessionid }}\"\n      state: acquire\n'''\n\nimport sys\n\ntry:\n    import consul\n    from requests.exceptions import ConnectionError\n    python_consul_installed = True\nexcept ImportError:\n    python_consul_installed = False\n\nfrom requests.exceptions import ConnectionError\n\ndef execute(module):\n\n    state = module.params.get('state')\n\n    if state == 'acquire' or state == 'release':\n        lock(module, state)\n    if state == 'present':\n        add_value(module)\n    else:\n        remove_value(module)\n\n\ndef lock(module, state):\n\n    consul_api = get_consul_api(module)\n\n    session = module.params.get('session')\n    key = module.params.get('key')\n    value = module.params.get('value')\n\n    if not session:\n        module.fail(\n            msg='%s of lock for %s requested but no session supplied' %\n            (state, key))\n\n    index, existing = consul_api.kv.get(key)\n\n    changed = not existing or (existing and existing['Value'] != value)\n    if changed and not module.check_mode:\n        if state == 'acquire':\n            changed = consul_api.kv.put(key, value,\n                                        cas=module.params.get('cas'),\n                                        acquire=session,\n                                        flags=module.params.get('flags'))\n        else:\n            changed = consul_api.kv.put(key, value,\n                                        cas=module.params.get('cas'),\n                                        release=session,\n                                        flags=module.params.get('flags'))\n\n    module.exit_json(changed=changed,\n                     index=index,\n                     key=key)\n\n\ndef add_value(module):\n\n    consul_api = get_consul_api(module)\n\n    key = module.params.get('key')\n    value = module.params.get('value')\n\n    index, existing = consul_api.kv.get(key)\n\n    changed = not existing or (existing and existing['Value'] != value)\n    if changed and not module.check_mode:\n        changed = consul_api.kv.put(key, value,\n                                    cas=module.params.get('cas'),\n                                    flags=module.params.get('flags'))\n\n    if module.params.get('retrieve'):\n        index, stored = consul_api.kv.get(key)\n\n    module.exit_json(changed=changed,\n                     index=index,\n                     key=key,\n                     data=stored)\n\n\ndef remove_value(module):\n    ''' remove the value associated with the given key. if the recurse parameter\n     is set then any key prefixed with the given key will be removed. '''\n    consul_api = get_consul_api(module)\n\n    key = module.params.get('key')\n    value = module.params.get('value')\n\n    index, existing = consul_api.kv.get(\n        key, recurse=module.params.get('recurse'))\n\n    changed = existing != None\n    if changed and not module.check_mode:\n        consul_api.kv.delete(key, module.params.get('recurse'))\n\n    module.exit_json(changed=changed,\n                     index=index,\n                     key=key,\n                     data=existing)\n\n\ndef get_consul_api(module, token=None):\n    return consul.Consul(host=module.params.get('host'),\n                         port=module.params.get('port'),\n                         scheme=module.params.get('scheme'),\n                         verify=module.params.get('validate_certs'),\n                         token=module.params.get('token'))\n\ndef test_dependencies(module):\n    if not python_consul_installed:\n        module.fail_json(msg=\"python-consul required for this module. \"\\\n              \"see http://python-consul.readthedocs.org/en/latest/#installation\")\n\ndef main():\n\n    argument_spec = dict(\n        cas=dict(required=False),\n        flags=dict(required=False),\n        key=dict(required=True),\n        host=dict(default='localhost'),\n        scheme=dict(required=False, default='http'),\n        validate_certs=dict(required=False, default=True),\n        port=dict(default=8500, type='int'),\n        recurse=dict(required=False, type='bool'),\n        retrieve=dict(required=False, default=True),\n        state=dict(default='present', choices=['present', 'absent', 'acquire', 'release']),\n        token=dict(required=False, no_log=True),\n        value=dict(required=False),\n        session=dict(required=False)\n    )\n\n    module = AnsibleModule(argument_spec, supports_check_mode=False)\n\n    test_dependencies(module)\n\n    try:\n        execute(module)\n    except ConnectionError as e:\n        module.fail_json(msg='Could not connect to consul agent at %s:%s, error was %s' % (\n                            module.params.get('host'), module.params.get('port'), str(e)))\n    except Exception as e:\n        module.fail_json(msg=str(e))\n\n\n# import module snippets\nfrom ansible.module_utils.basic import *\nif __name__ == '__main__':\n    main()\n", "path": "clustering/consul_kv.py"}]}