Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_net_subnet.py

raw
1 #!/usr/bin/python
2 # (c) 2018-2025, NetApp, Inc
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8 DOCUMENTATION = """
9 module: na_ontap_net_subnet
10 short_description: NetApp ONTAP Create, delete, modify network subnets.
11 extends_documentation_fragment:
12 - netapp.ontap.netapp.na_ontap
13 version_added: 2.8.0
14 author: Storage Engineering (@Albinpopote) <[email protected]>
15 description:
16 - Create, modify, destroy the network subnet
17 options:
18 state:
19 description:
20 - Whether the specified network interface group should exist or not.
21 choices: ['present', 'absent']
22 default: present
23 type: str
24
25 broadcast_domain:
26 description:
27 - Specify the required broadcast_domain name for the subnet.
28 - A broadcast domain can not be modified after the subnet has been created
29 type: str
30
31 name:
32 description:
33 - Specify the subnet name.
34 required: true
35 type: str
36
37 from_name:
38 description:
39 - Name of the subnet to be renamed
40 type: str
41
42 gateway:
43 description:
44 - Specify the gateway for the default route of the subnet.
45 type: str
46
47 ipspace:
48 description:
49 - Specify the ipspace for the subnet.
50 - The default value for this parameter is the default IPspace, named 'Default'.
51 type: str
52
53 ip_ranges:
54 description:
55 - Specify the list of IP address ranges associated with the subnet.
56 type: list
57 elements: str
58
59 subnet:
60 description:
61 - Specify the subnet (ip and mask).
62 type: str
63
64 notes:
65 - supports ZAPI and REST. REST requires ONTAP 9.11.1 or later.
66 - supports check mode.
67 """
68
69 EXAMPLES = """
70 - name: Create subnet
71 netapp.ontap.na_ontap_net_subnet:
72 state: present
73 username: "{{ netapp_username }}"
74 password: "{{ netapp_password }}"
75 hostname: "{{ netapp_hostname }}"
76 subnet: 10.10.10.0/24
77 name: subnet-adm
78 ip_ranges: ['10.10.10.30-10.10.10.40', '10.10.10.51']
79 gateway: 10.10.10.254
80 ipspace: Default
81 broadcast_domain: Default
82
83 - name: Delete subnet
84 netapp.ontap.na_ontap_net_subnet:
85 state: absent
86 username: "{{ netapp_username }}"
87 password: "{{ netapp_password }}"
88 hostname: "{{ netapp_hostname }}"
89 name: subnet-adm
90 ipspace: Default
91
92 - name: Rename subnet
93 netapp.ontap.na_ontap_net_subnet:
94 state: present
95 username: "{{ netapp_username }}"
96 password: "{{ netapp_password }}"
97 hostname: "{{ netapp_hostname }}"
98 name: subnet-adm-new
99 from_name: subnet-adm
100 ipspace: Default
101 """
102
103 RETURN = """
104
105 """
106
107 import traceback
108
109 from ansible.module_utils.basic import AnsibleModule
110 from ansible.module_utils._text import to_native
111 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
112 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
113 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
114
115
116 class NetAppOntapSubnet:
117 """
118 Create, Modifies and Destroys a subnet
119 """
120 def __init__(self):
121 """
122 Initialize the ONTAP Subnet class
123 """
124 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
125 self.argument_spec.update(dict(
126 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
127 name=dict(required=True, type='str'),
128 from_name=dict(required=False, type='str'),
129 broadcast_domain=dict(required=False, type='str'),
130 gateway=dict(required=False, type='str'),
131 ip_ranges=dict(required=False, type='list', elements='str'),
132 ipspace=dict(required=False, type='str'),
133 subnet=dict(required=False, type='str')
134 ))
135
136 self.module = AnsibleModule(
137 argument_spec=self.argument_spec,
138 supports_check_mode=True
139 )
140 self.na_helper = NetAppModule()
141 self.parameters = self.na_helper.set_parameters(self.module.params)
142 # Set up Rest API
143 self.rest_api = netapp_utils.OntapRestAPI(self.module)
144 self.use_rest = self.rest_api.is_rest()
145 self.uuid = None
146
147 if self.use_rest and not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 11, 1):
148 msg = 'REST requires ONTAP 9.11.1 or later for network/ip/subnets APIs.'
149 self.use_rest = self.na_helper.fall_back_to_zapi(self.module, msg, self.parameters)
150
151 if not self.use_rest:
152 if not netapp_utils.has_netapp_lib():
153 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
154 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
155
156 def get_subnet(self, name=None):
157 """
158 Return details about the subnet
159 :param:
160 name : Name of the subnet
161 :return: Details about the subnet. None if not found.
162 :rtype: dict
163 """
164 if name is None:
165 name = self.parameters.get('name')
166 if self.use_rest:
167 return self.get_subnet_rest(name)
168 subnet_iter = netapp_utils.zapi.NaElement('net-subnet-get-iter')
169 subnet_info = netapp_utils.zapi.NaElement('net-subnet-info')
170 subnet_info.add_new_child('subnet-name', name)
171 if self.parameters.get('ipspace'):
172 subnet_info.add_new_child('ipspace', self.parameters['ipspace'])
173 query = netapp_utils.zapi.NaElement('query')
174 query.add_child_elem(subnet_info)
175
176 subnet_iter.add_child_elem(query)
177 try:
178 result = self.server.invoke_successfully(subnet_iter, True)
179 except netapp_utils.zapi.NaApiError as error:
180 self.module.fail_json(msg='Error fetching subnet %s: %s' % (name, to_native(error)))
181 return_value = None
182 # check if query returns the expected subnet
183 if result.get_child_by_name('num-records') and \
184 int(result.get_child_content('num-records')) == 1:
185
186 subnet_attributes = result.get_child_by_name('attributes-list').get_child_by_name('net-subnet-info')
187 broadcast_domain = subnet_attributes.get_child_content('broadcast-domain')
188 gateway = subnet_attributes.get_child_content('gateway')
189 ipspace = subnet_attributes.get_child_content('ipspace')
190 subnet = subnet_attributes.get_child_content('subnet')
191 name = subnet_attributes.get_child_content('subnet-name')
192
193 ip_ranges = []
194 if subnet_attributes.get_child_by_name('ip-ranges'):
195 range_obj = subnet_attributes.get_child_by_name('ip-ranges').get_children()
196 ip_ranges = [elem.get_content() for elem in range_obj]
197
198 return_value = {
199 'name': name,
200 'broadcast_domain': broadcast_domain,
201 'gateway': gateway,
202 'ip_ranges': ip_ranges,
203 'ipspace': ipspace,
204 'subnet': subnet
205 }
206
207 return return_value
208
209 def create_subnet(self):
210 """
211 Creates a new subnet
212 """
213 if self.use_rest:
214 return self.create_subnet_rest()
215 subnet_create = self.build_zapi_request_for_create_or_modify('net-subnet-create')
216 try:
217 self.server.invoke_successfully(subnet_create, True)
218 except netapp_utils.zapi.NaApiError as error:
219 self.module.fail_json(msg='Error creating subnet %s: %s' % (self.parameters.get('name'), to_native(error)),
220 exception=traceback.format_exc())
221
222 def delete_subnet(self):
223 """
224 Deletes a subnet
225 """
226 if self.use_rest:
227 return self.delete_subnet_rest()
228 subnet_delete = netapp_utils.zapi.NaElement.create_node_with_children(
229 'net-subnet-destroy', **{'subnet-name': self.parameters.get('name')})
230 if self.parameters.get('ipspace'):
231 subnet_delete.add_new_child('ipspace', self.parameters.get('ipspace'))
232
233 try:
234 self.server.invoke_successfully(subnet_delete, True)
235 except netapp_utils.zapi.NaApiError as error:
236 self.module.fail_json(msg='Error deleting subnet %s: %s' % (self.parameters.get('name'), to_native(error)),
237 exception=traceback.format_exc())
238
239 def modify_subnet(self, modify):
240 """
241 Modifies a subnet
242 """
243 if self.use_rest:
244 return self.modify_subnet_rest(modify)
245 subnet_modify = self.build_zapi_request_for_create_or_modify('net-subnet-modify')
246 try:
247 self.server.invoke_successfully(subnet_modify, True)
248 except netapp_utils.zapi.NaApiError as error:
249 self.module.fail_json(msg='Error modifying subnet %s: %s' % (self.parameters.get('name'), to_native(error)),
250 exception=traceback.format_exc())
251
252 def build_zapi_request_for_create_or_modify(self, zapi):
253 simple_keys = ['gateway', 'ipspace', 'subnet']
254
255 # required parameters
256 options = {'subnet-name': self.parameters.get('name')}
257 if zapi == 'net-subnet-create':
258 options['broadcast-domain'] = self.parameters.get('broadcast_domain')
259 options['subnet'] = self.parameters.get('subnet')
260 simple_keys.remove('subnet')
261
262 # optional parameters
263 for key in simple_keys:
264 value = self.parameters.get(key)
265 if value is not None:
266 options[key] = value
267
268 result = netapp_utils.zapi.NaElement.create_node_with_children(zapi, **options)
269 if self.parameters.get('ip_ranges'):
270 subnet_ips = netapp_utils.zapi.NaElement('ip-ranges')
271 for ip_range in self.parameters.get('ip_ranges'):
272 subnet_ips.add_new_child('ip-range', ip_range)
273 result.add_child_elem(subnet_ips)
274
275 return result
276
277 def rename_subnet(self):
278 """
279 TODO
280 """
281 options = {'subnet-name': self.parameters.get('from_name'),
282 'new-name': self.parameters.get('name')}
283
284 subnet_rename = netapp_utils.zapi.NaElement.create_node_with_children(
285 'net-subnet-rename', **options)
286
287 if self.parameters.get('ipspace'):
288 subnet_rename.add_new_child('ipspace', self.parameters.get('ipspace'))
289
290 try:
291 self.server.invoke_successfully(subnet_rename, True)
292 except netapp_utils.zapi.NaApiError as error:
293 self.module.fail_json(msg='Error renaming subnet %s: %s' % (self.parameters.get('name'), to_native(error)),
294 exception=traceback.format_exc())
295
296 def get_subnet_rest(self, name):
297 api = 'network/ip/subnets'
298 params = {
299 'name': name,
300 'fields': 'available_ip_ranges,name,broadcast_domain,ipspace,gateway,subnet,uuid'
301 }
302 if self.parameters.get('ipspace'):
303 params['ipspace.name'] = self.parameters['ipspace']
304 record, error = rest_generic.get_one_record(self.rest_api, api, params)
305 if error:
306 self.module.fail_json(msg="Error fetching subnet %s: %s" % (name, error))
307 current = None
308 if record:
309 self.uuid = record['uuid']
310 current = {
311 'name': record['name'],
312 'broadcast_domain': self.na_helper.safe_get(record, ['broadcast_domain', 'name']),
313 'gateway': self.na_helper.safe_get(record, ['gateway']),
314 'ipspace': self.na_helper.safe_get(record, ['ipspace', 'name']),
315 'subnet': record['subnet']['address'] + '/' + record['subnet']['netmask'],
316 'ip_ranges': []
317 }
318 for each_range in record.get('available_ip_ranges', []):
319 if each_range['start'] == each_range['end']:
320 current['ip_ranges'].append(each_range['start'])
321 else:
322 current['ip_ranges'].append(each_range['start'] + '-' + each_range['end'])
323 return current
324
325 def create_subnet_rest(self):
326 api = 'network/ip/subnets'
327 dummy, error = rest_generic.post_async(self.rest_api, api, self.form_create_modify_body_rest())
328 if error:
329 self.module.fail_json(msg='Error creating subnet %s: %s' % (self.parameters['name'], to_native(error)))
330
331 def modify_subnet_rest(self, modify):
332 api = 'network/ip/subnets'
333 dummy, error = rest_generic.patch_async(self.rest_api, api, self.uuid, self.form_create_modify_body_rest(modify))
334 if error:
335 self.module.fail_json(msg='Error modifying subnet %s: %s' % (self.parameters.get('name'), to_native(error)))
336
337 def delete_subnet_rest(self):
338 api = 'network/ip/subnets'
339 dummy, error = rest_generic.delete_async(self.rest_api, api, self.uuid)
340 if error:
341 self.module.fail_json(msg='Error deleting subnet %s: %s' % (self.parameters.get('name'), to_native(error)))
342
343 def form_create_modify_body_rest(self, params=None):
344 if params is None:
345 params = self.parameters
346 body = {'name': self.parameters['name']}
347 if params.get('broadcast_domain'):
348 body['broadcast_domain.name'] = params['broadcast_domain']
349 if params.get('subnet'):
350 if '/' not in params['subnet']:
351 self.module.fail_json(msg="Error: Invalid value specified for subnet %s" % params['subnet'])
352 body['subnet.address'] = params['subnet'].split('/')[0]
353 body['subnet.netmask'] = params['subnet'].split('/')[1]
354 if params.get('gateway'):
355 body['gateway'] = params['gateway']
356 if params.get('ipspace'):
357 body['ipspace.name'] = params['ipspace']
358 ip_ranges = []
359 for each_range in params.get('ip_ranges', []):
360 if '-' in each_range:
361 ip_ranges.append({
362 'start': each_range.split('-')[0],
363 'end': each_range.split('-')[1]
364 })
365 else:
366 ip_ranges.append({
367 'start': each_range,
368 'end': each_range
369 })
370 if ip_ranges or params.get('ip_ranges') == []:
371 body['ip_ranges'] = ip_ranges
372 return body
373
374 def apply(self):
375 '''Apply action to subnet'''
376 current = self.get_subnet()
377 rename, modify = None, None
378
379 cd_action = self.na_helper.get_cd_action(current, self.parameters)
380 if cd_action == 'create' and self.parameters.get('from_name'):
381 # creating new subnet by renaming
382 current = self.get_subnet(self.parameters.get('from_name'))
383 if current is None:
384 self.module.fail_json(msg="Error renaming: subnet %s does not exist" %
385 self.parameters.get('from_name'))
386 rename = True
387 cd_action = None
388 if self.use_rest:
389 # patch takes care of renaming subnet too.
390 rename = False
391
392 if self.parameters['state'] == 'present' and current:
393 if not self.use_rest:
394 current.pop('name', None) # handled in rename
395 modify = self.na_helper.get_modified_attributes(current, self.parameters)
396 if 'broadcast_domain' in modify:
397 self.module.fail_json(msg='Error modifying subnet %s: cannot modify broadcast_domain parameter, desired "%s", currrent "%s"'
398 % (self.parameters.get('name'), self.parameters.get('broadcast_domain'), current.get('broadcast_domain')))
399
400 if cd_action == 'create':
401 for attribute in ['subnet', 'broadcast_domain']:
402 if not self.parameters.get(attribute):
403 self.module.fail_json(msg='Error - missing required arguments: %s.' % attribute)
404
405 if self.na_helper.changed and not self.module.check_mode:
406 if rename:
407 self.rename_subnet()
408 # If rename is True, cd_action is None but modify could be true
409 if cd_action == 'create':
410 self.create_subnet()
411 elif cd_action == 'delete':
412 self.delete_subnet()
413 elif modify:
414 self.modify_subnet(modify)
415 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
416 self.module.exit_json(**result)
417
418
419 def main():
420 """
421 Creates the NetApp ONTAP Net Route object and runs the correct play task
422 """
423 subnet_obj = NetAppOntapSubnet()
424 subnet_obj.apply()
425
426
427 if __name__ == '__main__':
428 main()