| 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_vlan_policy |
| 16 |
short_description: Manage VLAN Policies and VLANs for Cisco Intersight |
| 17 |
description: |
| 18 |
- Create, update, and delete VLAN Policies on Cisco Intersight. |
| 19 |
- Manage individual VLANs within VLAN policies. |
| 20 |
- Supports both regular VLANs and Private VLANs (Primary, Isolated, Community) configurations. |
| 21 |
- VLAN policies define network segmentation and can be attached to LAN Connectivity policies and Server Profiles. |
| 22 |
- For more information see L(Cisco Intersight,https://intersight.com/apidocs/fabric/EthNetworkPolicy/get/). |
| 23 |
extends_documentation_fragment: intersight |
| 24 |
options: |
| 25 |
state: |
| 26 |
description: |
| 27 |
- If C(present), will verify the resource is present and will create if needed. |
| 28 |
- If C(absent), will verify the resource is absent and will delete if needed. |
| 29 |
type: str |
| 30 |
choices: [present, absent] |
| 31 |
default: present |
| 32 |
organization: |
| 33 |
description: |
| 34 |
- The name of the Organization this resource is assigned to. |
| 35 |
- Policies created within a Custom Organization are applicable only to devices in the same Organization. |
| 36 |
- Use 'default' for the default organization. |
| 37 |
type: str |
| 38 |
default: default |
| 39 |
name: |
| 40 |
description: |
| 41 |
- The name assigned to the VLAN Policy. |
| 42 |
- Must be unique within the organization. |
| 43 |
- The name must be between 1 and 62 alphanumeric characters, allowing special characters :-_. |
| 44 |
type: str |
| 45 |
required: true |
| 46 |
description: |
| 47 |
description: |
| 48 |
- The user-defined description for the VLAN Policy. |
| 49 |
- Description can contain letters(a-z, A-Z), numbers(0-9), hyphen(-), period(.), colon(:), or an underscore(_). |
| 50 |
type: str |
| 51 |
aliases: [descr] |
| 52 |
tags: |
| 53 |
description: |
| 54 |
- List of tags in Key:<user-defined key> Value:<user-defined value> format. |
| 55 |
type: list |
| 56 |
elements: dict |
| 57 |
vlans: |
| 58 |
description: |
| 59 |
- List of VLANs to be created and attached to the VLAN policy. |
| 60 |
- Each VLAN will be named as C(prefix_vlan_id) (e.g., prod_100). |
| 61 |
- Leave empty to create a policy without VLANs for manual configuration later. |
| 62 |
type: list |
| 63 |
elements: dict |
| 64 |
suboptions: |
| 65 |
prefix: |
| 66 |
description: |
| 67 |
- Prefix for the VLAN name. |
| 68 |
- Combined with vlan_id to create the full VLAN name (prefix_vlan_id). |
| 69 |
type: str |
| 70 |
required: true |
| 71 |
vlan_id: |
| 72 |
description: |
| 73 |
- Enter a valid VLAN ID or ID range between 2 and 4093. |
| 74 |
- You can enter a range of IDs using a hyphen (e.g., "30-40" will create VLANs 30 through 40). |
| 75 |
- Examples of valid VLAN IDs or ID ranges are 50, 200, "2000-2100". |
| 76 |
- You cannot use VLANs from 4043-4047, 4094, and 4095 because these IDs are reserved for system use. |
| 77 |
- You can create a maximum of 3000 VLANs at a time. |
| 78 |
- VLAN ID - single ID 100 or range "30-40" (ranges require quotes). |
| 79 |
- Must be unique within the fabric interconnect domain. |
| 80 |
- When using ranges, multiple VLANs will be created with names following the pattern prefix_vlanid. |
| 81 |
- For non-contiguous VLANs, create separate VLAN blocks rather than using comma-separated values. |
| 82 |
type: str |
| 83 |
required: true |
| 84 |
is_native: |
| 85 |
description: |
| 86 |
- Whether this VLAN is the native VLAN for the fabric interconnect domain. |
| 87 |
type: bool |
| 88 |
default: false |
| 89 |
auto_allow_on_uplinks: |
| 90 |
description: |
| 91 |
- Whether to automatically allow this VLAN on uplinks. |
| 92 |
type: bool |
| 93 |
default: true |
| 94 |
enable_sharing: |
| 95 |
description: |
| 96 |
- When selected, enables Private VLAN sharing options. |
| 97 |
type: bool |
| 98 |
default: false |
| 99 |
multicast_policy_name: |
| 100 |
description: |
| 101 |
- Name of the multicast policy to associate with this VLAN. |
| 102 |
- Required when enable_sharing is false. |
| 103 |
type: str |
| 104 |
sharing_type: |
| 105 |
description: |
| 106 |
- Type of VLAN sharing when enable_sharing is true. |
| 107 |
- Use lowercase values (primary, isolated, community). |
| 108 |
type: str |
| 109 |
choices: ['primary', 'isolated', 'community'] |
| 110 |
primary_vlan_id: |
| 111 |
description: |
| 112 |
- The Primary VLAN ID of the VLAN, if the sharing type of the VLAN is Isolated or Community. |
| 113 |
type: int |
| 114 |
state: |
| 115 |
description: |
| 116 |
- Whether to create/update or delete the VLAN. |
| 117 |
type: str |
| 118 |
choices: ['present', 'absent'] |
| 119 |
default: present |
| 120 |
author: |
| 121 |
- Ron Gershburg (@rgershbu) |
| 122 |
''' |
| 123 |
|
| 124 |
EXAMPLES = r''' |
| 125 |
- name: Create a VLAN Policy with multiple VLANs |
| 126 |
cisco.intersight.intersight_vlan_policy: |
| 127 |
api_private_key: "{{ api_private_key }}" |
| 128 |
api_key_id: "{{ api_key_id }}" |
| 129 |
organization: "default" |
| 130 |
name: "datacenter-vlan-policy" |
| 131 |
description: "VLAN policy for datacenter infrastructure" |
| 132 |
tags: |
| 133 |
- Key: "Environment" |
| 134 |
Value: "Production" |
| 135 |
- Key: "Site" |
| 136 |
Value: "DataCenter-A" |
| 137 |
vlans: |
| 138 |
- prefix: "prod" |
| 139 |
vlan_id: 100 |
| 140 |
auto_allow_on_uplinks: true |
| 141 |
enable_sharing: false |
| 142 |
multicast_policy_name: "default-multicast-policy" |
| 143 |
- prefix: "dev" |
| 144 |
vlan_id: 200 |
| 145 |
auto_allow_on_uplinks: false |
| 146 |
enable_sharing: false |
| 147 |
multicast_policy_name: "default-multicast-policy" |
| 148 |
- prefix: "mgmt" |
| 149 |
vlan_id: 300 |
| 150 |
auto_allow_on_uplinks: true |
| 151 |
enable_sharing: false |
| 152 |
multicast_policy_name: "default-multicast-policy" |
| 153 |
is_native: true |
| 154 |
state: present |
| 155 |
|
| 156 |
- name: Create a VLAN Policy with VLAN sharing (Private VLANs) |
| 157 |
cisco.intersight.intersight_vlan_policy: |
| 158 |
api_private_key: "{{ api_private_key }}" |
| 159 |
api_key_id: "{{ api_key_id }}" |
| 160 |
organization: "default" |
| 161 |
name: "private-vlan-policy" |
| 162 |
description: "Policy with private VLAN configuration" |
| 163 |
vlans: |
| 164 |
- prefix: "primary" |
| 165 |
vlan_id: 79 |
| 166 |
enable_sharing: true |
| 167 |
sharing_type: "primary" |
| 168 |
auto_allow_on_uplinks: true |
| 169 |
- prefix: "isolated" |
| 170 |
vlan_id: 90 |
| 171 |
enable_sharing: true |
| 172 |
sharing_type: "isolated" |
| 173 |
primary_vlan_id: 79 |
| 174 |
auto_allow_on_uplinks: true |
| 175 |
- prefix: "community" |
| 176 |
vlan_id: 91 |
| 177 |
enable_sharing: true |
| 178 |
sharing_type: "community" |
| 179 |
primary_vlan_id: 79 |
| 180 |
auto_allow_on_uplinks: true |
| 181 |
state: present |
| 182 |
|
| 183 |
- name: Create a VLAN Policy with mixed configurations |
| 184 |
cisco.intersight.intersight_vlan_policy: |
| 185 |
api_private_key: "{{ api_private_key }}" |
| 186 |
api_key_id: "{{ api_key_id }}" |
| 187 |
organization: "Engineering" |
| 188 |
name: "mixed-vlan-policy" |
| 189 |
description: "Mixed configuration with shared and non-shared VLANs" |
| 190 |
vlans: |
| 191 |
- prefix: "web" |
| 192 |
vlan_id: 10 |
| 193 |
auto_allow_on_uplinks: true |
| 194 |
enable_sharing: false |
| 195 |
multicast_policy_name: "web-multicast-policy" |
| 196 |
- prefix: "db" |
| 197 |
vlan_id: 20 |
| 198 |
auto_allow_on_uplinks: false |
| 199 |
enable_sharing: false |
| 200 |
state: absent |
| 201 |
multicast_policy_name: "db-multicast-policy" |
| 202 |
- prefix: "dmz_primary" |
| 203 |
vlan_id: 50 |
| 204 |
enable_sharing: true |
| 205 |
sharing_type: "primary" |
| 206 |
auto_allow_on_uplinks: true |
| 207 |
state: present |
| 208 |
- prefix: "dmz_isolated" |
| 209 |
vlan_id: 51 |
| 210 |
enable_sharing: true |
| 211 |
sharing_type: "isolated" |
| 212 |
primary_vlan_id: 50 |
| 213 |
auto_allow_on_uplinks: true |
| 214 |
state: present |
| 215 |
|
| 216 |
- name: Create a VLAN Policy with VLAN ranges |
| 217 |
cisco.intersight.intersight_vlan_policy: |
| 218 |
api_private_key: "{{ api_private_key }}" |
| 219 |
api_key_id: "{{ api_key_id }}" |
| 220 |
organization: "default" |
| 221 |
name: "range-vlan-policy" |
| 222 |
description: "Policy with VLAN ranges" |
| 223 |
vlans: |
| 224 |
- prefix: "prod" |
| 225 |
vlan_id: "30-40" |
| 226 |
auto_allow_on_uplinks: true |
| 227 |
enable_sharing: false |
| 228 |
multicast_policy_name: "default-multicast-policy" |
| 229 |
- prefix: "dev" |
| 230 |
vlan_id: "100-110" |
| 231 |
auto_allow_on_uplinks: true |
| 232 |
enable_sharing: false |
| 233 |
multicast_policy_name: "default-multicast-policy" |
| 234 |
- prefix: "mgmt" |
| 235 |
vlan_id: 200 |
| 236 |
auto_allow_on_uplinks: true |
| 237 |
enable_sharing: false |
| 238 |
multicast_policy_name: "default-multicast-policy" |
| 239 |
state: present |
| 240 |
|
| 241 |
- name: Create a VLAN Policy with minimal configuration (policy only) |
| 242 |
cisco.intersight.intersight_vlan_policy: |
| 243 |
api_private_key: "{{ api_private_key }}" |
| 244 |
api_key_id: "{{ api_key_id }}" |
| 245 |
name: "empty-vlan-policy" |
| 246 |
description: "Empty policy for manual VLAN configuration" |
| 247 |
state: present |
| 248 |
|
| 249 |
- name: Update an existing VLAN Policy |
| 250 |
cisco.intersight.intersight_vlan_policy: |
| 251 |
api_private_key: "{{ api_private_key }}" |
| 252 |
api_key_id: "{{ api_key_id }}" |
| 253 |
name: "datacenter-vlan-policy" |
| 254 |
description: "Updated description for datacenter infrastructure" |
| 255 |
tags: |
| 256 |
- Key: "Environment" |
| 257 |
Value: "Production" |
| 258 |
- Key: "Site" |
| 259 |
Value: "DataCenter-A" |
| 260 |
- Key: "Updated" |
| 261 |
Value: "2024-01-01" |
| 262 |
state: present |
| 263 |
|
| 264 |
- name: Delete a VLAN Policy |
| 265 |
cisco.intersight.intersight_vlan_policy: |
| 266 |
api_private_key: "{{ api_private_key }}" |
| 267 |
api_key_id: "{{ api_key_id }}" |
| 268 |
name: "datacenter-vlan-policy" |
| 269 |
state: absent |
| 270 |
''' |
| 271 |
|
| 272 |
RETURN = r''' |
| 273 |
api_response: |
| 274 |
description: The API response output returned by the specified resource. |
| 275 |
returned: always |
| 276 |
type: dict |
| 277 |
sample: |
| 278 |
"api_response": { |
| 279 |
"Name": "test_vlan_policy", |
| 280 |
"ObjectType": "fabric.EthNetworkPolicy", |
| 281 |
"Tags": [ |
| 282 |
{ |
| 283 |
"Key": "Site", |
| 284 |
"Value": "DataCenter-A" |
| 285 |
} |
| 286 |
] |
| 287 |
} |
| 288 |
''' |
| 289 |
|
| 290 |
|
| 291 |
from ansible.module_utils.basic import AnsibleModule |
| 292 |
from ansible_collections.cisco.intersight.plugins.module_utils.intersight import IntersightModule, intersight_argument_spec, compare_values |
| 293 |
|
| 294 |
|
| 295 |
def parse_vlan_id_range(vlan_id_input): |
| 296 |
""" |
| 297 |
Parse VLAN ID input which can be: |
| 298 |
- String with single ID: "100" |
| 299 |
- String with range: "100-110" |
| 300 |
Args: |
| 301 |
vlan_id_input: VLAN ID as string |
| 302 |
Returns: |
| 303 |
List of individual VLAN IDs |
| 304 |
Raises: |
| 305 |
ValueError: If the input format is invalid |
| 306 |
""" |
| 307 |
vlan_ids = [] |
| 308 |
# Parse string input |
| 309 |
vlan_id_str = str(vlan_id_input).strip() |
| 310 |
# Check for comma-separated values and reject them |
| 311 |
if ',' in vlan_id_str: |
| 312 |
raise ValueError("Comma-separated VLAN IDs are not supported. Please create separate VLAN blocks for non-contiguous VLANs") |
| 313 |
if '-' in vlan_id_str: |
| 314 |
# Range format: "100-110" |
| 315 |
try: |
| 316 |
start, end = vlan_id_str.split('-', 1) |
| 317 |
start_id = int(start.strip()) |
| 318 |
end_id = int(end.strip()) |
| 319 |
if start_id > end_id: |
| 320 |
raise ValueError(f"Invalid VLAN range {vlan_id_str}: start ID must be less than or equal to end ID") |
| 321 |
vlan_ids.extend(range(start_id, end_id + 1)) |
| 322 |
except ValueError as e: |
| 323 |
if "Comma-separated" in str(e): |
| 324 |
raise |
| 325 |
raise ValueError(f"Invalid VLAN range format '{vlan_id_str}': {str(e)}") |
| 326 |
else: |
| 327 |
# Single ID |
| 328 |
try: |
| 329 |
vlan_ids.append(int(vlan_id_str)) |
| 330 |
except ValueError: |
| 331 |
raise ValueError(f"Invalid VLAN ID '{vlan_id_str}': must be an integer") |
| 332 |
return vlan_ids |
| 333 |
|
| 334 |
|
| 335 |
def validate_vlan_id(vlan_id): |
| 336 |
""" |
| 337 |
Validate a VLAN ID is within acceptable ranges. |
| 338 |
Valid range: 1-4094, excluding 4043-4047, 4094, 4095 |
| 339 |
Args: |
| 340 |
vlan_id: VLAN ID to validate |
| 341 |
Raises: |
| 342 |
ValueError: If VLAN ID is invalid or reserved |
| 343 |
Returns: |
| 344 |
True if valid |
| 345 |
""" |
| 346 |
reserved_vlans = [4094, 4095] + list(range(4043, 4048)) |
| 347 |
if vlan_id < 1 or vlan_id > 4094: |
| 348 |
raise ValueError(f"VLAN ID {vlan_id} is out of valid range (1-4094)") |
| 349 |
if vlan_id in reserved_vlans: |
| 350 |
raise ValueError(f"VLAN ID {vlan_id} is reserved for system use (4043-4047, 4094, 4095)") |
| 351 |
return True |
| 352 |
|
| 353 |
|
| 354 |
def get_vlans_map_for_policy(intersight, vlan_policy_moid, top=1000): |
| 355 |
""" |
| 356 |
Fetch all VLANs for a given VLAN policy and build lookup maps. |
| 357 |
|
| 358 |
Args: |
| 359 |
intersight: IntersightModule instance |
| 360 |
vlan_policy_moid: VLAN policy MOID |
| 361 |
top: Page size for pagination (will be capped to 1000) |
| 362 |
|
| 363 |
Returns: |
| 364 |
dict -> VLAN object (keyed by VlanId) |
| 365 |
""" |
| 366 |
if top <= 0: |
| 367 |
top = 1000 |
| 368 |
if top > 1000: |
| 369 |
top = 1000 |
| 370 |
|
| 371 |
filter_str = f"EthNetworkPolicy.Moid eq '{vlan_policy_moid}'" |
| 372 |
resource_path = '/fabric/Vlans' |
| 373 |
|
| 374 |
count_options = { |
| 375 |
'http_method': 'get', |
| 376 |
'resource_path': resource_path, |
| 377 |
'query_params': { |
| 378 |
'$filter': filter_str, |
| 379 |
'$count': 'true' |
| 380 |
}, |
| 381 |
} |
| 382 |
count_resp = intersight.call_api(**count_options) |
| 383 |
total_count = count_resp.get('Count', 0) |
| 384 |
if not isinstance(total_count, int) or total_count < 0: |
| 385 |
total_count = 0 |
| 386 |
|
| 387 |
pages = 0 |
| 388 |
if total_count > 0: |
| 389 |
# Calculate number of pages to fetch all VLANs |
| 390 |
pages = (total_count + top - 1) // top |
| 391 |
|
| 392 |
all_vlans = [] |
| 393 |
for page_idx in range(pages): |
| 394 |
skip = page_idx * top |
| 395 |
page_options = { |
| 396 |
'http_method': 'get', |
| 397 |
'resource_path': resource_path, |
| 398 |
'query_params': { |
| 399 |
'$filter': filter_str, |
| 400 |
'$top': top, |
| 401 |
'$skip': skip, |
| 402 |
}, |
| 403 |
} |
| 404 |
page_resp = intersight.call_api(**page_options) |
| 405 |
page_results = page_resp.get('Results') |
| 406 |
if isinstance(page_results, list) and page_results: |
| 407 |
all_vlans.extend(page_results) |
| 408 |
|
| 409 |
vlan_id_map = {} |
| 410 |
for vlan in all_vlans: |
| 411 |
vlan_id = vlan.get('VlanId') |
| 412 |
if isinstance(vlan_id, int): |
| 413 |
# VlanId is unique per policy; keep the first occurrence if duplicates appear due to paging instability. |
| 414 |
if vlan_id not in vlan_id_map: |
| 415 |
vlan_id_map[vlan_id] = vlan |
| 416 |
|
| 417 |
return vlan_id_map |
| 418 |
|
| 419 |
|
| 420 |
def build_vlan_sharing_config(enable_sharing, sharing_type, primary_vlan_id, multicast_policy_moid, is_patch=False): |
| 421 |
""" |
| 422 |
Build VLAN sharing configuration for POST or PATCH operations. |
| 423 |
|
| 424 |
Args: |
| 425 |
enable_sharing: Whether VLAN sharing is enabled |
| 426 |
sharing_type: Type of sharing (Primary, Isolated, Community) |
| 427 |
primary_vlan_id: Primary VLAN ID for Isolated/Community types |
| 428 |
multicast_policy_moid: MOID of multicast policy (if not sharing) |
| 429 |
is_patch: True for PATCH operations, False for POST operations |
| 430 |
|
| 431 |
Returns: |
| 432 |
Dictionary with SharingType, PrimaryVlanId, and optionally MulticastPolicy |
| 433 |
""" |
| 434 |
config = {} |
| 435 |
|
| 436 |
if enable_sharing: |
| 437 |
config['SharingType'] = sharing_type |
| 438 |
config['PrimaryVlanId'] = primary_vlan_id if sharing_type in ['Isolated', 'Community'] else 0 |
| 439 |
# For PATCH operations, explicitly set MulticastPolicy to None to clear it |
| 440 |
# when switching from non-shared to shared VLANs |
| 441 |
if is_patch: |
| 442 |
config['MulticastPolicy'] = None |
| 443 |
else: |
| 444 |
config['SharingType'] = 'None' |
| 445 |
config['PrimaryVlanId'] = 0 |
| 446 |
if multicast_policy_moid: |
| 447 |
config['MulticastPolicy'] = multicast_policy_moid |
| 448 |
|
| 449 |
return config |
| 450 |
|
| 451 |
|
| 452 |
def build_vlan_base_body(vlan_name, vlan_id, auto_allow_on_uplinks, is_native): |
| 453 |
""" |
| 454 |
Build base VLAN API body with common fields. |
| 455 |
|
| 456 |
Args: |
| 457 |
vlan_name: Name of the VLAN |
| 458 |
vlan_id: VLAN ID |
| 459 |
auto_allow_on_uplinks: Whether to auto-allow on uplinks |
| 460 |
is_native: Whether this is the native VLAN |
| 461 |
|
| 462 |
Returns: |
| 463 |
Dictionary with base VLAN fields |
| 464 |
""" |
| 465 |
return { |
| 466 |
'Name': vlan_name, |
| 467 |
'VlanId': vlan_id, |
| 468 |
'AutoAllowOnUplinks': auto_allow_on_uplinks, |
| 469 |
'IsNative': is_native |
| 470 |
} |
| 471 |
|
| 472 |
|
| 473 |
def build_vlan_body_for_post(vlan_name, vlan_id, auto_allow_on_uplinks, is_native, |
| 474 |
enable_sharing, sharing_type, primary_vlan_id, |
| 475 |
multicast_policy_moid, vlan_policy_moid): |
| 476 |
""" |
| 477 |
Build VLAN API body for POST (create) operations. |
| 478 |
|
| 479 |
Args: |
| 480 |
vlan_policy_moid: MOID of the parent VLAN policy (required for POST) |
| 481 |
|
| 482 |
Returns: |
| 483 |
Complete API body for VLAN creation |
| 484 |
""" |
| 485 |
body = build_vlan_base_body(vlan_name, vlan_id, auto_allow_on_uplinks, is_native) |
| 486 |
body['EthNetworkPolicy'] = vlan_policy_moid |
| 487 |
body.update(build_vlan_sharing_config(enable_sharing, sharing_type, primary_vlan_id, multicast_policy_moid, is_patch=False)) |
| 488 |
return body |
| 489 |
|
| 490 |
|
| 491 |
def build_vlan_body_for_patch(vlan_name, vlan_id, auto_allow_on_uplinks, is_native, |
| 492 |
enable_sharing, sharing_type, primary_vlan_id, multicast_policy_moid): |
| 493 |
""" |
| 494 |
Build VLAN API body for PATCH (update) operations. |
| 495 |
|
| 496 |
Note: Excludes EthNetworkPolicy as it cannot be changed after creation. |
| 497 |
For PATCH operations, MulticastPolicy is explicitly set to None when switching |
| 498 |
to shared VLANs to clear any previously configured multicast policy. |
| 499 |
|
| 500 |
Returns: |
| 501 |
API body for VLAN update |
| 502 |
""" |
| 503 |
body = build_vlan_base_body(vlan_name, vlan_id, auto_allow_on_uplinks, is_native) |
| 504 |
body.update(build_vlan_sharing_config(enable_sharing, sharing_type, primary_vlan_id, multicast_policy_moid, is_patch=True)) |
| 505 |
return body |
| 506 |
|
| 507 |
|
| 508 |
def main(): |
| 509 |
argument_spec = intersight_argument_spec.copy() |
| 510 |
argument_spec.update( |
| 511 |
state=dict(type='str', choices=['present', 'absent'], default='present'), |
| 512 |
organization=dict(type='str', default='default'), |
| 513 |
name=dict(type='str', required=True), |
| 514 |
description=dict(type='str', aliases=['descr']), |
| 515 |
tags=dict(type='list', elements='dict'), |
| 516 |
vlans=dict(type='list', elements='dict', options=dict( |
| 517 |
prefix=dict(type='str', required=True), |
| 518 |
vlan_id=dict(type='str', required=True), |
| 519 |
auto_allow_on_uplinks=dict(type='bool', default=True), |
| 520 |
enable_sharing=dict(type='bool', default=False), |
| 521 |
multicast_policy_name=dict(type='str'), |
| 522 |
sharing_type=dict(type='str', choices=['primary', 'isolated', 'community']), |
| 523 |
primary_vlan_id=dict(type='int'), |
| 524 |
is_native=dict(type='bool', default=False), |
| 525 |
state=dict(type='str', choices=['present', 'absent'], default='present') |
| 526 |
)) |
| 527 |
) |
| 528 |
module = AnsibleModule( |
| 529 |
argument_spec, |
| 530 |
supports_check_mode=True, |
| 531 |
) |
| 532 |
|
| 533 |
intersight = IntersightModule(module) |
| 534 |
# Initialize structured response |
| 535 |
final_response = { |
| 536 |
'vlan_policy': {}, |
| 537 |
'vlans': [] |
| 538 |
} |
| 539 |
|
| 540 |
# Initialize list to track changed states from each API call |
| 541 |
changed_states = [] |
| 542 |
|
| 543 |
# Resource path used to configure policy |
| 544 |
resource_path = '/fabric/EthNetworkPolicies' |
| 545 |
# Define API body used in compares or create |
| 546 |
intersight.api_body = { |
| 547 |
'Organization': { |
| 548 |
'Name': intersight.module.params['organization'], |
| 549 |
}, |
| 550 |
'Name': intersight.module.params['name'] |
| 551 |
} |
| 552 |
if intersight.module.params['state'] == 'present': |
| 553 |
intersight.set_tags_and_description() |
| 554 |
|
| 555 |
intersight.configure_policy_or_profile(resource_path=resource_path) |
| 556 |
|
| 557 |
# Store the VLAN policy response |
| 558 |
final_response['vlan_policy'] = intersight.result['api_response'] |
| 559 |
|
| 560 |
# Save the changed state and reset for next operation |
| 561 |
changed_states.append(intersight.result['changed']) |
| 562 |
intersight.result['changed'] = False |
| 563 |
|
| 564 |
vlan_policy_moid = None |
| 565 |
if intersight.module.params['state'] == 'present' and final_response['vlan_policy']: |
| 566 |
vlan_policy_moid = final_response['vlan_policy'].get('Moid') |
| 567 |
|
| 568 |
# Process VLANs if provided |
| 569 |
if intersight.module.params['state'] == 'present' and intersight.module.params['vlans']: |
| 570 |
# Check if we have a valid VLAN policy MOID before processing VLANs |
| 571 |
if not vlan_policy_moid: |
| 572 |
if intersight.module.check_mode: |
| 573 |
# In check mode, policy doesn't exist yet, skip VLAN processing |
| 574 |
final_response['vlans'] = [] |
| 575 |
else: |
| 576 |
# This shouldn't happen - policy should exist before processing VLANs |
| 577 |
module.fail_json(msg="VLAN policy MOID is missing, verify vlan policy was created by the module") |
| 578 |
else: |
| 579 |
# Cache for multicast policy MOIDs to avoid redundant API calls |
| 580 |
multicast_policy_cache = {} |
| 581 |
vlan_id_map = {} |
| 582 |
|
| 583 |
# Build all VLAN configurations and validate |
| 584 |
vlan_operations = {'create': [], 'update': [], 'delete': []} |
| 585 |
|
| 586 |
for vlan_config in intersight.module.params['vlans']: |
| 587 |
# Parse VLAN ID range to get list of individual VLAN IDs |
| 588 |
try: |
| 589 |
vlan_ids = parse_vlan_id_range(vlan_config['vlan_id']) |
| 590 |
except ValueError as e: |
| 591 |
module.fail_json(msg=f"Error parsing vlan_id '{vlan_config['vlan_id']}': {str(e)}") |
| 592 |
|
| 593 |
# Validate each VLAN ID |
| 594 |
for vlan_id in vlan_ids: |
| 595 |
try: |
| 596 |
validate_vlan_id(vlan_id) |
| 597 |
except ValueError as e: |
| 598 |
module.fail_json(msg=str(e)) |
| 599 |
|
| 600 |
# Extract configuration |
| 601 |
prefix = vlan_config['prefix'] |
| 602 |
auto_allow_on_uplinks = vlan_config.get('auto_allow_on_uplinks') |
| 603 |
enable_sharing = vlan_config.get('enable_sharing') |
| 604 |
is_native = vlan_config.get('is_native') |
| 605 |
vlan_state = vlan_config.get('state', 'present') |
| 606 |
|
| 607 |
# Process each VLAN ID in the range |
| 608 |
for vlan_id in vlan_ids: |
| 609 |
# Generate VLAN name: prefix_vlan_id |
| 610 |
vlan_name = f"{prefix}_{vlan_id}" |
| 611 |
|
| 612 |
# Resolve multicast policy MOID / sharing config only when VLAN is being created/updated |
| 613 |
multicast_policy_moid = None |
| 614 |
sharing_type = None |
| 615 |
primary_vlan_id_value = 0 |
| 616 |
if vlan_state == 'present': |
| 617 |
if enable_sharing: |
| 618 |
sharing_type_raw = vlan_config.get('sharing_type') |
| 619 |
if not sharing_type_raw: |
| 620 |
module.fail_json( |
| 621 |
msg=f"Configuration error for VLAN '{vlan_name}': sharing_type is required when enable_sharing is true. " |
| 622 |
f"Valid options: 'primary', 'isolated', or 'community'. " |
| 623 |
f"Example: sharing_type: 'primary'" |
| 624 |
) |
| 625 |
# Normalize lowercase input to proper case for API |
| 626 |
sharing_type_map = {'primary': 'Primary', 'isolated': 'Isolated', 'community': 'Community'} |
| 627 |
sharing_type = sharing_type_map.get(sharing_type_raw) |
| 628 |
if sharing_type not in ['Primary', 'Isolated', 'Community']: |
| 629 |
module.fail_json( |
| 630 |
msg=f"Configuration error for VLAN '{vlan_name}': Invalid sharing_type '{sharing_type_raw}'. " |
| 631 |
f"Valid options are: 'primary', 'isolated', or 'community'" |
| 632 |
) |
| 633 |
if sharing_type in ['Isolated', 'Community']: |
| 634 |
if 'primary_vlan_id' not in vlan_config: |
| 635 |
module.fail_json( |
| 636 |
msg=f"Configuration error for VLAN '{vlan_name}': primary_vlan_id is required when sharing_type is '{sharing_type}'. " |
| 637 |
f"Specify the VLAN ID of the Primary VLAN. " |
| 638 |
f"Example: primary_vlan_id: 79" |
| 639 |
) |
| 640 |
primary_vlan_id_value = vlan_config['primary_vlan_id'] |
| 641 |
else: |
| 642 |
multicast_policy_name = vlan_config.get('multicast_policy_name') |
| 643 |
if not multicast_policy_name: |
| 644 |
module.fail_json( |
| 645 |
msg=f"Configuration error for VLAN prefix '{prefix}': multicast_policy_name is required when enable_sharing is false. " |
| 646 |
f"Specify the name of an existing multicast policy. " |
| 647 |
f"Example: multicast_policy_name: 'default'" |
| 648 |
) |
| 649 |
if multicast_policy_name in multicast_policy_cache: |
| 650 |
multicast_policy_moid = multicast_policy_cache[multicast_policy_name] |
| 651 |
else: |
| 652 |
multicast_policy_moid = intersight.get_moid_by_name_and_org( |
| 653 |
resource_path='/fabric/MulticastPolicies', |
| 654 |
resource_name=multicast_policy_name, |
| 655 |
organization_name=intersight.module.params['organization'] |
| 656 |
) |
| 657 |
if not multicast_policy_moid: |
| 658 |
module.fail_json( |
| 659 |
msg=f"Multicast policy '{multicast_policy_name}' not found in organization '{intersight.module.params['organization']}'" |
| 660 |
) |
| 661 |
multicast_policy_cache[multicast_policy_name] = multicast_policy_moid |
| 662 |
|
| 663 |
# Build VLAN-ID map only once (after we know the policy MOID and before we start checking VLANs) |
| 664 |
if not vlan_id_map: |
| 665 |
vlan_id_map = get_vlans_map_for_policy( |
| 666 |
intersight=intersight, |
| 667 |
vlan_policy_moid=vlan_policy_moid, |
| 668 |
top=1000 |
| 669 |
) |
| 670 |
|
| 671 |
# Check if VLAN already exists using cached map (VlanId is unique per policy) |
| 672 |
existing_vlan = vlan_id_map.get(vlan_id, {}) |
| 673 |
|
| 674 |
existing_moid = existing_vlan.get('Moid') |
| 675 |
custom_filter = f"VlanId eq {vlan_id} and EthNetworkPolicy.Moid eq '{vlan_policy_moid}'" |
| 676 |
|
| 677 |
# Determine operation type |
| 678 |
if vlan_state == 'present': |
| 679 |
if existing_moid: |
| 680 |
# VLAN exists, check if update is needed |
| 681 |
# Build body for PATCH (without EthNetworkPolicy, proper object references) |
| 682 |
vlan_patch_body = build_vlan_body_for_patch( |
| 683 |
vlan_name=vlan_name, |
| 684 |
vlan_id=vlan_id, |
| 685 |
auto_allow_on_uplinks=auto_allow_on_uplinks, |
| 686 |
is_native=is_native, |
| 687 |
enable_sharing=enable_sharing, |
| 688 |
sharing_type=sharing_type, |
| 689 |
primary_vlan_id=primary_vlan_id_value, |
| 690 |
multicast_policy_moid=multicast_policy_moid |
| 691 |
) |
| 692 |
if not compare_values(vlan_patch_body, existing_vlan): |
| 693 |
vlan_operations['update'].append({ |
| 694 |
'body': vlan_patch_body, |
| 695 |
'moid': existing_moid, |
| 696 |
'name': vlan_name, |
| 697 |
'filter': custom_filter |
| 698 |
}) |
| 699 |
else: |
| 700 |
# VLAN exists and matches, add to response but no change needed |
| 701 |
final_response['vlans'].append(existing_vlan) |
| 702 |
else: |
| 703 |
# VLAN doesn't exist, needs to be created |
| 704 |
# Build body for POST (includes EthNetworkPolicy) |
| 705 |
vlan_post_body = build_vlan_body_for_post( |
| 706 |
vlan_name=vlan_name, |
| 707 |
vlan_id=vlan_id, |
| 708 |
auto_allow_on_uplinks=auto_allow_on_uplinks, |
| 709 |
is_native=is_native, |
| 710 |
enable_sharing=enable_sharing, |
| 711 |
sharing_type=sharing_type, |
| 712 |
primary_vlan_id=primary_vlan_id_value, |
| 713 |
multicast_policy_moid=multicast_policy_moid, |
| 714 |
vlan_policy_moid=vlan_policy_moid |
| 715 |
) |
| 716 |
vlan_operations['create'].append({ |
| 717 |
'body': vlan_post_body, |
| 718 |
'name': vlan_name, |
| 719 |
'filter': custom_filter |
| 720 |
}) |
| 721 |
else: # state == 'absent' |
| 722 |
if existing_moid: |
| 723 |
vlan_operations['delete'].append({ |
| 724 |
'moid': existing_moid, |
| 725 |
'name': vlan_name, |
| 726 |
'body': { |
| 727 |
'VlanId': vlan_id |
| 728 |
} |
| 729 |
}) |
| 730 |
|
| 731 |
# Execute bulk operations |
| 732 |
bulk_results = intersight.execute_bulk_operations( |
| 733 |
resource_path='/fabric/Vlans', |
| 734 |
operations_dict=vlan_operations, |
| 735 |
changed_states=changed_states |
| 736 |
) |
| 737 |
final_response['vlans'].extend(bulk_results) |
| 738 |
|
| 739 |
# Set the final structured response |
| 740 |
intersight.result['api_response'] = final_response |
| 741 |
|
| 742 |
# Set final changed state based on whether any operation resulted in a change |
| 743 |
intersight.result['changed'] = any(changed_states) |
| 744 |
|
| 745 |
module.exit_json(**intersight.result) |
| 746 |
|
| 747 |
|
| 748 |
if __name__ == '__main__': |
| 749 |
main() |