Debian Codegraph @

ansible_collections/kubernetes/core/plugins/module_utils/common.py

raw symbols SCIP
1 # Copyright 2018 Red Hat | Ansible
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
18 from __future__ import absolute_import, division, print_function
19
20 __metaclass__ = type
21
22 import base64
23 import os
24 from tempfile import NamedTemporaryFile
25
26 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
27 from ansible.module_utils.urls import Request
28
29 try:
30 import urllib3
31
32 urllib3.disable_warnings()
33 except ImportError:
34 pass
35
36
37 def fetch_file_from_url(module, url):
38 # Download file
39 bufsize = 65536
40 file_name, file_ext = os.path.splitext(str(url.rsplit("/", 1)[1]))
41 temp_file = NamedTemporaryFile(
42 dir=module.tmpdir, prefix=file_name, suffix=file_ext, delete=False
43 )
44 module.add_cleanup_file(temp_file.name)
45 try:
46 rsp = Request().open("GET", url)
47 if not rsp:
48 module.fail_json(msg="Failure downloading %s" % url)
49 data = rsp.read(bufsize)
50 while data:
51 temp_file.write(data)
52 data = rsp.read(bufsize)
53 temp_file.close()
54 except Exception as e:
55 module.fail_json(msg="Failure downloading %s, %s" % (url, to_native(e)))
56 return temp_file.name
57
58
59 def _encode_stringdata(definition):
60 if definition["kind"] == "Secret" and "stringData" in definition:
61 for k, v in definition["stringData"].items():
62 encoded = base64.b64encode(to_bytes(v))
63 definition.setdefault("data", {})[k] = to_text(encoded)
64 del definition["stringData"]
65 return definition