Debian Codegraph @

ansible_collections/community/clickhouse/plugins/modules/clickhouse_cfg_info.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2024, Andrew Klychkov (@Andersson007) <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import (absolute_import, division, print_function)
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: clickhouse_cfg_info
13
14 short_description: Retrieves ClickHouse config file content and returns it as JSON
15
16 version_added: '0.7.0'
17
18 description:
19 - Retrieves ClickHouse config file content and returns it as JSON.
20 - Supports config files in the YAML and XML formats.
21 - Does not change server state.
22
23 attributes:
24 check_mode:
25 description: Supports check_mode.
26 support: full
27
28 author:
29 - Andrew Klychkov (@Andersson007)
30
31 options:
32 path:
33 description:
34 - Path to the config file.
35 type: path
36 required: true
37
38 requirements:
39 - pyyaml (for YAML config files)
40 - xmltodict (for XML config files)
41 '''
42
43 EXAMPLES = r'''
44 - name: Get server information
45 register: result
46 community.clickhouse.clickhouse_cfg_info:
47 path: /etc/clickhouse-server/config.yaml
48
49 - name: Print returned data
50 ansible.builtin.debug:
51 var: result
52 '''
53
54 RETURN = r'''
55 config:
56 description:
57 - The content of the config file.
58 returned: success
59 type: dict
60 '''
61
62 try:
63 import yaml
64 HAS_PYYAML = True
65 except ImportError:
66 HAS_PYYAML = False
67
68 try:
69 import xmltodict
70 HAS_XMLTODICT = True
71 except ImportError:
72 HAS_XMLTODICT = False
73
74 from ansible.module_utils.basic import (
75 AnsibleModule,
76 missing_required_lib,
77 )
78 import json
79
80
81 def load_config(module, load_func, path):
82 try:
83 f = open(path, 'r')
84 content = load_func(f)
85 except Exception as e:
86 fail_msg = "Could not open/load from file %s: %s" % (path, e)
87 module.fail_json(msg=fail_msg)
88 else:
89 f.close()
90 return content
91
92
93 def load_from_yaml(f):
94 item = yaml.safe_load(f)
95 # Ensure structure is JSON-serializable to prevent hangs from recursive aliases
96 # See: https://github.com/ansible-collections/community.clickhouse/issues/111
97 json.dumps(item)
98 return item
99
100
101 def load_from_xml(f):
102 content = xmltodict.parse(f.read())['clickhouse']
103 # This lib loads all values including boolean
104 # or numerical as strings. Let's convert if possible.
105 return convert_str_vals_in_dict(content)
106
107
108 def is_xml(path):
109 return True if len(path) > 4 and path[-4:] == '.xml' else False
110
111
112 def convert_str_vals_in_dict(d):
113 """Recursively traverse a dict and covert
114 string values to appropirate types.
115 """
116 for key, val in d.items():
117 if isinstance(val, dict):
118 convert_str_vals_in_dict(val)
119
120 elif isinstance(val, list):
121 for i, v in enumerate(val):
122 if isinstance(v, dict):
123 convert_str_vals_in_dict(val[i])
124 else:
125 d[key] = convert(val)
126
127 return d
128
129
130 def convert(val):
131 # Try to convert or just return it back
132 try:
133 if val == 'false':
134 val = False
135 elif val == 'true':
136 val = True
137 elif val.isnumeric():
138 val = int(val)
139 else:
140 val = float(val)
141 except Exception:
142 return val
143
144 return val
145
146
147 def main():
148 argument_spec = {}
149 argument_spec.update(
150 path=dict(type='path', required=True),
151 )
152
153 # Instantiate an object of module class
154 module = AnsibleModule(
155 argument_spec=argument_spec,
156 supports_check_mode=True,
157 )
158
159 path = module.params['path']
160
161 # When XML
162 if is_xml(path):
163 if not HAS_XMLTODICT:
164 module.fail_json(msg=missing_required_lib('xmltodict'))
165 load_func = load_from_xml
166
167 # When YAML, the default
168 else:
169 if not HAS_PYYAML:
170 module.fail_json(msg=missing_required_lib('pyyaml'))
171 load_func = load_from_yaml
172
173 # Load content as dict
174 cfg_content = load_config(module, load_func, path)
175
176 # Users will get this in JSON output after execution
177 module.exit_json(changed=False, config=cfg_content)
178
179
180 if __name__ == '__main__':
181 main()