Debian Codegraph @

ansible_collections/cisco/intersight/plugins/modules/intersight_ethernet_network_group_policy.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 ANSIBLE_METADATA = {'metadata_version': '1.1',
10 'status': ['preview'],
11 'supported_by': 'community'}
12
13 DOCUMENTATION = r'''
14 ---
15 module: intersight_ethernet_network_group_policy
16 short_description: Ethernet Network Group Policy configuration for Cisco Intersight
17 description:
18 - Manages Ethernet Network Group Policy configuration on Cisco Intersight.
19 - A policy to configure VLAN settings and QinQ (802.1Q-in-802.1Q) tunneling for Ethernet virtual interfaces on Cisco Intersight managed servers.
20 - For more information see L(Cisco Intersight,https://intersight.com/apidocs/fabric/EthNetworkGroupPolicy/get/).
21 extends_documentation_fragment: intersight
22 options:
23 state:
24 description:
25 - If C(present), will verify the resource is present and will create if needed.
26 - If C(absent), will verify the resource is absent and will delete if needed.
27 - When C(absent), VLAN configuration parameters are not required.
28 type: str
29 choices: [present, absent]
30 default: present
31 organization:
32 description:
33 - The name of the Organization this resource is assigned to.
34 - Profiles, Policies, and Pools that are created within a Custom Organization are applicable only to devices in the same Organization.
35 type: str
36 default: default
37 name:
38 description:
39 - The name assigned to the Ethernet Network Group Policy.
40 - The name must be between 1 and 62 alphanumeric characters, allowing special characters :-_.
41 type: str
42 required: true
43 description:
44 description:
45 - The user-defined description for the Ethernet Network Group Policy.
46 - Description can contain letters(a-z, A-Z), numbers(0-9), hyphen(-), period(.), colon(:), or an underscore(_).
47 type: str
48 aliases: [descr]
49 tags:
50 description:
51 - List of tags in Key:<user-defined key> Value:<user-defined value> format.
52 type: list
53 elements: dict
54 qinq_enabled:
55 description:
56 - Enable QinQ (802.1Q-in-802.1Q) Tunneling on the vNIC.
57 - When enabled, C(qinq_vlan) is required and C(allowed_vlans) is ignored.
58 - When disabled, C(allowed_vlans) is required.
59 type: bool
60 default: false
61 qinq_vlan:
62 description:
63 - Set QinQ VLAN number.
64 - Required when C(qinq_enabled) is true.
65 - Only one QinQ VLAN can be specified.
66 - Valid range is 2-4093.
67 type: int
68 native_vlan:
69 description:
70 - Set native VLAN for the Ethernet Network Group Policy.
71 - Can be used with QinQ (when C(qinq_enabled) is true) or with regular VLAN mode (when C(qinq_enabled) is false).
72 - When used with C(allowed_vlans), the native VLAN must be included in the allowed VLANs list.
73 - Only one native VLAN can be specified.
74 - Valid range is 1-4093.
75 type: int
76 allowed_vlans:
77 description:
78 - Include VLAN IDs using a list of comma separated VLAN IDs and VLAN ID Ranges.
79 - Required when C(qinq_enabled) is false.
80 - Examples of valid formats are C(1), C(1,2,3,4,8), C(1-4,7), C(1-8,12,16).
81 - Valid VLAN range is 1-4093.
82 type: str
83 author:
84 - Ron Gershburg (@rgershbu)
85 '''
86
87 EXAMPLES = r'''
88 - name: Create an Ethernet Network Group Policy with regular VLANs
89 cisco.intersight.intersight_ethernet_network_group_policy:
90 api_private_key: "{{ api_private_key }}"
91 api_key_id: "{{ api_key_id }}"
92 organization: "default"
93 name: "regular-vlans-policy"
94 description: "Policy with regular VLAN configuration"
95 qinq_enabled: false
96 allowed_vlans: "1-8,12,16"
97 state: present
98
99 - name: Create an Ethernet Network Group Policy with QinQ enabled
100 cisco.intersight.intersight_ethernet_network_group_policy:
101 api_private_key: "{{ api_private_key }}"
102 api_key_id: "{{ api_key_id }}"
103 organization: "default"
104 name: "qinq-policy"
105 description: "Policy with QinQ configuration"
106 tags:
107 - Key: "Environment"
108 Value: "Production"
109 qinq_enabled: true
110 qinq_vlan: 4
111 native_vlan: 1
112 state: present
113
114 - name: Create an Ethernet Network Group Policy with QinQ enabled (no native VLAN)
115 cisco.intersight.intersight_ethernet_network_group_policy:
116 api_private_key: "{{ api_private_key }}"
117 api_key_id: "{{ api_key_id }}"
118 name: "qinq-no-native-policy"
119 description: "QinQ policy without native VLAN"
120 qinq_enabled: true
121 qinq_vlan: 100
122 state: present
123
124 - name: Create an Ethernet Network Group Policy with single VLAN
125 cisco.intersight.intersight_ethernet_network_group_policy:
126 api_private_key: "{{ api_private_key }}"
127 api_key_id: "{{ api_key_id }}"
128 name: "single-vlan-policy"
129 description: "Policy with single VLAN"
130 qinq_enabled: false
131 allowed_vlans: "50"
132 state: present
133
134 - name: Create an Ethernet Network Group Policy with native VLAN
135 cisco.intersight.intersight_ethernet_network_group_policy:
136 api_private_key: "{{ api_private_key }}"
137 api_key_id: "{{ api_key_id }}"
138 name: "native-vlan-policy"
139 description: "Policy with allowed VLANs and native VLAN"
140 qinq_enabled: false
141 allowed_vlans: "1-100,200-300"
142 native_vlan: 1
143 state: present
144
145 - name: Delete an Ethernet Network Group Policy
146 cisco.intersight.intersight_ethernet_network_group_policy:
147 api_private_key: "{{ api_private_key }}"
148 api_key_id: "{{ api_key_id }}"
149 name: "qinq-policy"
150 state: absent
151 '''
152
153 RETURN = r'''
154 api_response:
155 description: The API response output returned by the specified resource.
156 returned: always
157 type: dict
158 sample:
159 "api_response": {
160 "Name": "regular-vlans-policy",
161 "ObjectType": "fabric.EthNetworkGroupPolicy",
162 "VlanSettings": {
163 "ClassId": "fabric.VlanSettings",
164 "ObjectType": "fabric.VlanSettings",
165 "QinqEnabled": false,
166 "AllowedVlans": "1-5,10,15-20"
167 },
168 "Tags": [
169 {
170 "Key": "Environment",
171 "Value": "Prod"
172 }
173 ]
174 }
175 '''
176
177
178 import re
179 from ansible.module_utils.basic import AnsibleModule
180 from ansible_collections.cisco.intersight.plugins.module_utils.intersight import IntersightModule, intersight_argument_spec
181
182
183 def validate_allowed_vlans_format(allowed_vlans):
184 """Validate allowed_vlans format and return parsed VLAN IDs"""
185 if not allowed_vlans or not allowed_vlans.strip():
186 return False, "allowed_vlans cannot be empty"
187
188 # Remove all whitespace
189 vlans_str = allowed_vlans.replace(' ', '')
190
191 # Pattern to match: single VLAN (123) or VLAN range (123-456)
192 # Full pattern: comma-separated list of single VLANs or ranges
193 pattern = r'^(\d+(-\d+)?)(,\d+(-\d+)?)*$'
194
195 if not re.match(pattern, vlans_str):
196 return False, "allowed_vlans must be in format '1', '1,2,3', '1-4', or '1-4,7,10-15'"
197
198 # Parse and validate individual VLAN IDs and ranges
199 vlan_parts = vlans_str.split(',')
200 for part in vlan_parts:
201 if '-' in part:
202 try:
203 start, end = part.split('-')
204 start_id, end_id = int(start), int(end)
205 if start_id >= end_id:
206 return False, f"Invalid VLAN range '{part}': start must be less than end"
207 if start_id < 1 or start_id > 4093 or end_id < 1 or end_id > 4093:
208 return False, f"VLAN IDs in range '{part}' must be between 1 and 4093"
209 except ValueError:
210 return False, f"Invalid VLAN range format '{part}'"
211 else:
212 # Validate single vlan
213 try:
214 vlan_id = int(part)
215 if vlan_id < 1 or vlan_id > 4093:
216 return False, f"VLAN ID '{vlan_id}' must be between 1 and 4093"
217 except ValueError:
218 return False, f"Invalid VLAN ID '{part}'"
219
220 return True, None
221
222
223 def is_vlan_in_allowed_vlans(vlan_id, allowed_vlans_str):
224 """Check if a VLAN ID is included in the allowed VLANs string"""
225 # Remove all whitespace
226 vlans_str = allowed_vlans_str.replace(' ', '')
227 vlan_parts = vlans_str.split(',')
228
229 for part in vlan_parts:
230 if '-' in part:
231 # VLAN range
232 start, end = part.split('-')
233 start_id, end_id = int(start), int(end)
234 if start_id <= vlan_id <= end_id:
235 return True
236 else:
237 # Single VLAN
238 if int(part) == vlan_id:
239 return True
240
241 return False
242
243
244 def validate_vlan_ranges(module):
245 """Validate VLAN range values and required parameters"""
246 state = module.params.get('state')
247 qinq_enabled = module.params.get('qinq_enabled')
248 qinq_vlan = module.params.get('qinq_vlan')
249 native_vlan = module.params.get('native_vlan')
250 allowed_vlans = module.params.get('allowed_vlans')
251
252 if state == 'present':
253 if qinq_enabled:
254 # When qinq_enabled is true, qinq_vlan is required
255 if not qinq_vlan:
256 module.fail_json(msg='missing required arguments: qinq_vlan')
257 else:
258 # When qinq_enabled is false, allowed_vlans is required
259 if not allowed_vlans:
260 module.fail_json(msg='missing required arguments: allowed_vlans')
261
262 if qinq_vlan and (qinq_vlan < 2 or qinq_vlan > 4093):
263 module.fail_json(msg='qinq_vlan must be between 2 and 4093')
264
265 if native_vlan and (native_vlan < 1 or native_vlan > 4093):
266 module.fail_json(msg='native_vlan must be between 1 and 4093')
267
268 # Validate allowed_vlans format if provided and clean it
269 if allowed_vlans:
270 is_valid, error_msg = validate_allowed_vlans_format(allowed_vlans)
271 if not is_valid:
272 module.fail_json(msg=error_msg)
273 # Store the cleaned version (whitespace removed) back to module.params
274 module.params['allowed_vlans'] = allowed_vlans.replace(' ', '')
275
276 # Validate native_vlan is in allowed_vlans when both are specified
277 if native_vlan and allowed_vlans and not qinq_enabled:
278 if not is_vlan_in_allowed_vlans(native_vlan, allowed_vlans):
279 module.fail_json(msg=f'native_vlan {native_vlan} must be included in allowed_vlans: {allowed_vlans}')
280
281
282 def main():
283 argument_spec = intersight_argument_spec.copy()
284 argument_spec.update(
285 state=dict(type='str', choices=['present', 'absent'], default='present'),
286 organization=dict(type='str', default='default'),
287 name=dict(type='str', required=True),
288 description=dict(type='str', aliases=['descr']),
289 tags=dict(type='list', elements='dict'),
290 qinq_enabled=dict(type='bool', default=False), # Verify that placing default works with required_if
291 qinq_vlan=dict(type='int'),
292 native_vlan=dict(type='int'),
293 allowed_vlans=dict(type='str'),
294 )
295 module = AnsibleModule(
296 argument_spec,
297 supports_check_mode=True,
298 mutually_exclusive=[
299 ['allowed_vlans', 'qinq_vlan'],
300 ],
301 )
302
303 validate_vlan_ranges(module)
304 intersight = IntersightModule(module)
305 intersight.result['api_response'] = {}
306 intersight.result['trace_id'] = ''
307
308 # Resource path used to configure policy
309 resource_path = '/fabric/EthNetworkGroupPolicies'
310
311 # Define API body used in compares or create
312 intersight.api_body = {
313 'Organization': {
314 'Name': intersight.module.params['organization'],
315 },
316 'Name': intersight.module.params['name']
317 }
318
319 if module.params['state'] == 'present':
320 intersight.set_tags_and_description()
321
322 # Build VlanSettings based on qinq_enabled
323 vlan_settings = {
324 'QinqEnabled': module.params['qinq_enabled']
325 }
326
327 if module.params['qinq_enabled']:
328 vlan_settings['QinqVlan'] = module.params['qinq_vlan']
329 if module.params['native_vlan']:
330 vlan_settings['NativeVlan'] = module.params['native_vlan']
331 else:
332 # Regular VLAN mode
333 vlan_settings['AllowedVlans'] = module.params['allowed_vlans']
334 if module.params['native_vlan']:
335 vlan_settings['NativeVlan'] = module.params['native_vlan']
336
337 intersight.api_body.update({
338 'VlanSettings': vlan_settings
339 })
340
341 intersight.configure_policy_or_profile(resource_path=resource_path)
342
343 module.exit_json(**intersight.result)
344
345
346 if __name__ == '__main__':
347 main()