Debian Codegraph @

ansible_collections/purestorage/flasharray/plugins/modules/purefa_ntp.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2018, Simon Dodsley ([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
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefa_ntp
20 version_added: '1.0.0'
21 short_description: Configure Pure Storage FlashArray NTP settings
22 description:
23 - Set, erase or test NTP configuration for Pure Storage FlashArrays.
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 state:
28 description:
29 - Create, delete or test NTP servers configuration
30 type: str
31 default: present
32 choices: [ absent, present, test ]
33 ntp_servers:
34 type: list
35 elements: str
36 description:
37 - A list of up to 4 alternate NTP servers. These may include IPv4,
38 IPv6 or FQDNs. Invalid IP addresses will cause the module to fail.
39 No validation is performed for FQDNs.
40 - If more than 4 servers are provided, only the first 4 unique
41 nameservers will be used.
42 - if no servers are given a default of I(0.pool.ntp.org) will be used.
43 ntp_key:
44 type: str
45 description:
46 - The NTP symmetric key to be used for NTP authentication.
47 - If it is an ASCII string, it cannot contain the character "#"
48 and cannot be longer than 20 characters.
49 - If it is a hex-encoded string, it cannot be longer than 64 characters.
50 - Setting this parameter is not idempotent.
51 version_added: "1.22.0"
52 context:
53 description:
54 - Name of fleet member on which to perform the ntp operation.
55 - This requires the array receiving the request is a member of a fleet
56 and the context name to be a member of the same fleet.
57 type: str
58 default: ""
59 version_added: '1.37.0'
60 extends_documentation_fragment:
61 - purestorage.flasharray.purestorage.fa
62 """
63
64 EXAMPLES = r"""
65 - name: Delete existing NTP server entries
66 purestorage.flasharray.purefa_ntp:
67 state: absent
68 fa_url: 10.10.10.2
69 api_token: e31060a7-21fc-e277-6240-25983c6c4592
70
71 - name: Set array NTP servers
72 purestorage.flasharray.purefa_ntp:
73 state: present
74 ntp_servers:
75 - "0.pool.ntp.org"
76 - "1.pool.ntp.org"
77 - "2.pool.ntp.org"
78 - "3.pool.ntp.org"
79 fa_url: 10.10.10.2
80 api_token: e31060a7-21fc-e277-6240-25983c6c4592
81 """
82
83 RETURN = r"""
84 """
85
86 from ansible.module_utils.basic import AnsibleModule
87 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
88 get_array,
89 purefa_argument_spec,
90 )
91 from ansible_collections.purestorage.flasharray.plugins.module_utils.version import (
92 LooseVersion,
93 )
94
95 HAS_PURESTORAGE = True
96 try:
97 from pypureclient.flasharray import Arrays
98 except ImportError:
99 HAS_PURESTORAGE = False
100
101
102 KEY_API_VERSION = "2.26"
103 CONTEXT_API_VERSION = "2.38"
104
105
106 def _is_cbs(array, is_cbs=False):
107 """Is the selected array a Cloud Block Store"""
108 # api_version = array.get_rest_version()
109 #
110 # Until get_controller has context_names we can check against a target system
111 # CBS can't be support for Fusion
112 #
113 # if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
114 # model = list(
115 # array.get_controllers(context_names=[module.params["context"]]).items
116 # )[0].model
117 # else:
118 model = list(array.get_controllers().items)[0].model
119 is_cbs = bool("CBS" in model)
120 return is_cbs
121
122
123 def remove(duplicate):
124 final_list = []
125 for num in duplicate:
126 if num not in final_list:
127 final_list.append(num)
128 return final_list
129
130
131 def test_ntp(module, array):
132 """Test NTP configuration"""
133 # api_version = array.get_rest_version()
134 test_response = []
135 #
136 # Until get_arrays_ntp_test has context_names we can check against a target system
137 # test_ntp is not supported with context
138 #
139 # if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
140 # response = list(array.get_arrays_ntp_test(context_names=[module.params["context"]]).items)
141 # else:
142 response = list(array.get_arrays_ntp_test().items)
143 for component in response:
144 if component.enabled:
145 enabled = "true"
146 else:
147 enabled = "false"
148 if component.success:
149 success = "true"
150 else:
151 success = "false"
152 test_response.append(
153 {
154 "component_address": component.component_address,
155 "component_name": component.component_name,
156 "description": component.description,
157 "destination": component.destination,
158 "enabled": enabled,
159 "result_details": getattr(component, "result_details", ""),
160 "success": success,
161 "test_type": component.test_type,
162 "resource_name": component.resource.name,
163 }
164 )
165 module.exit_json(changed=True, test_response=test_response)
166
167
168 def delete_ntp(module, array):
169 """Delete NTP Servers"""
170 api_version = array.get_rest_version()
171 changed = False
172 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
173 array_list = array.get_arrays(context_names=[module.params["context"]])
174 else:
175 array_list = array.get_arrays()
176 if list(array_list.items)[0].ntp_servers != []:
177 changed = True
178 if not module.check_mode:
179 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
180 res = array.patch_arrays(
181 array=Arrays(ntp_servers=[]),
182 context_names=[module.params["context"]],
183 )
184 else:
185 res = array.patch_arrays(array=Arrays(ntp_servers=[]))
186 if res.status_code != 200:
187 module.fail_json(
188 msg="Deletion of NTP servers failed. Error: {0}".format(
189 res.errors[0].message
190 )
191 )
192 module.exit_json(changed=changed)
193
194
195 def create_ntp(module, array):
196 """Set NTP Servers"""
197 api_version = array.get_rest_version()
198 changed = True
199 if not module.check_mode:
200 if not module.params["ntp_servers"]:
201 module.params["ntp_servers"] = ["0.pool.ntp.org"]
202 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
203 res = array.patch_arrays(
204 array=Arrays(ntp_servers=module.params["ntp_servers"][0:4]),
205 context_names=[module.params["context"]],
206 )
207 else:
208 res = array.patch_arrays(
209 array=Arrays(ntp_servers=module.params["ntp_servers"][0:4])
210 )
211 if res.status_code != 200:
212 module.fail_json(
213 msg="Update of NTP servers failed. Error: {0}".format(
214 res.errors[0].message
215 )
216 )
217 module.exit_json(changed=changed)
218
219
220 def update_ntp_key(module, array):
221 """Update NTP Symmetric Key"""
222 api_version = array.get_rest_version()
223 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
224 array_list = array.get_arrays(context_names=[module.params["context"]])
225 else:
226 array_list = array.get_arrays()
227 if module.params["ntp_key"] == "" and not getattr(
228 list(array_list.items)[0], "ntp_symmetric_key", None
229 ):
230 changed = False
231 else:
232 try:
233 int(module.params["ntp_key"], 16)
234 if len(module.params["ntp_key"]) > 64:
235 module.fail_json(msg="HEX string cannot be longer than 64 characters")
236 except ValueError:
237 if len(module.params["ntp_key"]) > 20:
238 module.fail_json(msg="ASCII string cannot be longer than 20 characters")
239 if "#" in module.params["ntp_key"]:
240 module.fail_json(msg="ASCII string cannot contain # character")
241 if not all(ord(c) < 128 for c in module.params["ntp_key"]):
242 module.fail_json(msg="NTP key is non-ASCII")
243 changed = True
244 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
245 res = array.patch_arrays(
246 array=Arrays(ntp_symmetric_key=module.params["ntp_key"]),
247 context_names=[module.params["context"]],
248 )
249 else:
250 res = array.patch_arrays(
251 array=Arrays(ntp_symmetric_key=module.params["ntp_key"])
252 )
253 if res.status_code != 200:
254 module.fail_json(
255 msg="Failed to update NTP Symmetric Key. Error: {0}".format(
256 res.errors[0].message
257 )
258 )
259 module.exit_json(changed=changed)
260
261 if len(module.params["ntp_key"]) > 20:
262 # Must be HEX string is greter than 20 characters
263 try:
264 int(module.params["ntp_key"], 16)
265 except ValueError:
266 module.fail_json(msg="NTP key is not HEX")
267
268
269 def main():
270 argument_spec = purefa_argument_spec()
271 argument_spec.update(
272 dict(
273 ntp_servers=dict(type="list", elements="str"),
274 ntp_key=dict(type="str", no_log=True),
275 state=dict(
276 type="str", default="present", choices=["absent", "present", "test"]
277 ),
278 context=dict(type="str", default=""),
279 )
280 )
281
282 module = AnsibleModule(argument_spec, supports_check_mode=True)
283 if not HAS_PURESTORAGE:
284 module.fail_json(msg="py-pure-client sdk is required for this module")
285
286 array = get_array(module)
287 api_version = array.get_rest_version()
288 if _is_cbs(array):
289 module.warn("NTP settings are not necessary for a CBS array - ignoring...")
290 module.exit_json(changed=False)
291
292 if module.params["state"] == "absent":
293 delete_ntp(module, array)
294 elif module.params["state"] == "test":
295 # Fail if context is set as not supported
296 if not module.params["context"]:
297 module.fail_json(msg="NTP testing is not supported with context")
298 test_ntp(module, array)
299 elif module.params["ntp_servers"]:
300 module.params["ntp_servers"] = remove(module.params["ntp_servers"])
301 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
302 array_list = array.get_arrays(context_names=[module.params["context"]])
303 else:
304 array_list = array.get_arrays()
305 if sorted(list(array_list.items)[0].ntp_servers) != sorted(
306 module.params["ntp_servers"][0:4]
307 ):
308 create_ntp(module, array)
309 if module.params["ntp_key"] or module.params["ntp_key"] == "":
310 if LooseVersion(KEY_API_VERSION) > LooseVersion(api_version):
311 module.fail_json(msg="REST API does not support setting NTP Symmetric Key")
312 else:
313 update_ntp_key(module, array)
314 module.exit_json(changed=False)
315
316
317 if __name__ == "__main__":
318 main()