Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_subnet.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016 Matt Davis, <[email protected]>
4 # Chris Houseknecht, <[email protected]>
5 #
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 ---
14 module: azure_rm_subnet
15 version_added: "0.1.0"
16 short_description: Manage Azure subnets
17 description:
18 - Create, update or delete a subnet within a given virtual network.
19 - Allows setting and updating the address prefix CIDR, which must be valid within the context of the virtual network.
20 - Use the M(azure.azcollection.azure_rm_networkinterface) module to associate interfaces with the subnet and assign specific IP addresses.
21 options:
22 resource_group:
23 description:
24 - Name of resource group.
25 required: true
26 type: str
27 name:
28 description:
29 - Name of the subnet.
30 required: true
31 type: str
32 address_prefix_cidr:
33 description:
34 - CIDR defining the IPv4 address space of the subnet. Must be valid within the context of the virtual network.
35 type: str
36 aliases:
37 - address_prefix
38 address_prefixes_cidr:
39 description:
40 - CIDR defining the IPv4 and IPv6 address space of the subnet. Must be valid within the context of the virtual network.
41 - If set I(address_prefix), It will not set.
42 aliases:
43 - address_prefixes
44 version_added: "1.0.0"
45 type: list
46 elements: str
47 security_group:
48 description:
49 - Existing security group with which to associate the subnet.
50 - It can be the security group name which is in the same resource group.
51 - Can be the resource ID of the security group.
52 - Can be a dict containing the I(name) and I(resource_group) of the security group.
53 type: raw
54 aliases:
55 - security_group_name
56 state:
57 description:
58 - Assert the state of the subnet. Use C(present) to create or update a subnet and use C(absent) to delete a subnet.
59 default: present
60 type: str
61 choices:
62 - absent
63 - present
64 virtual_network_name:
65 description:
66 - Name of an existing virtual network with which the subnet is or will be associated.
67 required: true
68 type: str
69 aliases:
70 - virtual_network
71 route_table:
72 description:
73 - The reference of the RouteTable resource.
74 - Can be the name or resource ID of the route table.
75 - Can be a dict containing the I(name) and I(resource_group) of the route table.
76 - Without this configuration, the associated route table will be dissociate. If there is no associated route table, it has no impact.
77 type: raw
78 service_endpoints:
79 description:
80 - An array of service endpoints.
81 type: list
82 elements: dict
83 suboptions:
84 service:
85 description:
86 - The type of the endpoint service.
87 required: True
88 type: str
89 locations:
90 description:
91 - A list of locations.
92 type: list
93 elements: str
94 private_endpoint_network_policies:
95 description:
96 - C(Enabled) or C(Disabled) apply network policies on private endpoints in the subnet.
97 type: str
98 default: Enabled
99 choices:
100 - Enabled
101 - Disabled
102 - NetworkSecurityGroupEnabled
103 - RouteTableEnabled
104 private_link_service_network_policies:
105 description:
106 - C(Enabled) or C(Disabled) apply network policies on private link service in the subnet.
107 type: str
108 default: Enabled
109 choices:
110 - Enabled
111 - Disabled
112 delegations:
113 description:
114 - An array of delegations.
115 type: list
116 elements: dict
117 suboptions:
118 name:
119 description:
120 - The name of delegation.
121 type: str
122 required: True
123 serviceName:
124 description:
125 - The type of the endpoint service.
126 required: True
127 type: str
128 choices:
129 - Microsoft.ContainerService/managedClusters
130 - Microsoft.Web/serverFarms
131 - Microsoft.ContainerInstance/containerGroups
132 - Microsoft.Netapp/volumes
133 - Microsoft.HardwareSecurityModules/dedicatedHSMs
134 - Microsoft.ServiceFabricMesh/networks
135 - Microsoft.Logic/integrationServiceEnvironments
136 - Microsoft.Batch/batchAccounts
137 - Microsoft.Sql/managedInstances
138 - Microsoft.Web/hostingEnvironments
139 - Microsoft.BareMetal/CrayServers
140 - Microsoft.BareMetal/MonitoringServers
141 - Microsoft.Databricks/workspaces
142 - Microsoft.BareMetal/AzureHostedService
143 - Microsoft.BareMetal/AzureVMware
144 - Microsoft.BareMetal/AzureHPC
145 - Microsoft.BareMetal/AzurePaymentHSM
146 - Microsoft.StreamAnalytics/streamingJobs
147 - Microsoft.DBforPostgreSQL/serversv2
148 - Microsoft.AzureCosmosDB/clusters
149 - Microsoft.MachineLearningServices/workspaces
150 - Microsoft.DBforPostgreSQL/singleServers
151 - Microsoft.DBforPostgreSQL/flexibleServers
152 - Microsoft.DBforMySQL/serversv2
153 - Microsoft.DBforMySQL/flexibleServers
154 - Microsoft.ApiManagement/service
155 - Microsoft.Synapse/workspaces
156 - Microsoft.PowerPlatform/vnetaccesslinks
157 - Microsoft.Network/managedResolvers
158 - Microsoft.Kusto/clusters
159 - Microsoft.App/environments
160 - Microsoft.Network/applicationGateways
161 actions:
162 description:
163 - A list of actions.
164 type: list
165 elements: str
166 default: []
167 nat_gateway:
168 description:
169 - Existing NAT Gateway with which to associate the subnet.
170 - It can be the NAT Gateway name which is in the same resource group.
171 - Can be the resource ID of the NAT Gateway.
172 - Can be a dict containing the I(name) and I(resource_group) of the NAT Gateway.
173 type: str
174 service_endpoint_policies:
175 description:
176 - An array of service endpoint policies.
177 type: list
178 elements: dict
179 suboptions:
180 id:
181 description:
182 - Resource ID of the service endpoint policy.
183 type: str
184 sharing_scope:
185 description:
186 - Set this property to Tenant to allow sharing subnet with other subscriptions in your AAD tenant.
187 type: str
188 choices:
189 - DelegatedServices
190 - Tenant
191 default_outbound_access:
192 description:
193 - Set this property to false to disable default outbound connectivity for all VMs in the subnet.
194 type: bool
195
196 extends_documentation_fragment:
197 - azure.azcollection.azure
198
199 author:
200 - Chris Houseknecht (@chouseknecht)
201 - Matt Davis (@nitzmahone)
202
203 '''
204
205 EXAMPLES = '''
206 - name: Create a subnet
207 azure_rm_subnet:
208 resource_group: myResourceGroup
209 virtual_network_name: myVirtualNetwork
210 name: mySubnet
211 address_prefix_cidr: "10.1.0.0/24"
212
213 - name: Create a subnet refer nsg from other resource group
214 azure_rm_subnet:
215 resource_group: myResourceGroup
216 virtual_network_name: myVirtualNetwork
217 name: mySubnet
218 address_prefix_cidr: "10.1.0.0/16"
219 security_group:
220 name: secgroupfoo
221 resource_group: mySecondResourceGroup
222 route_table: route
223
224 - name: Create a subnet with service endpoint
225 azure_rm_subnet:
226 resource_group: myResourceGroup
227 virtual_network_name: myVirtualNetwork
228 name: mySubnet
229 address_prefix_cidr: "10.1.0.0/16"
230 service_endpoints:
231 - service: "Microsoft.Sql"
232 locations:
233 - "eastus"
234
235 - name: Create a subnet with delegations
236 azure_rm_subnet:
237 resource_group: myResourceGroup
238 virtual_network_name: myVirtualNetwork
239 name: mySubnet
240 address_prefix_cidr: "10.1.0.0/16"
241 delegations:
242 - name: 'mydeleg'
243 serviceName: 'Microsoft.ContainerInstance/containerGroups'
244
245 - name: Create a subnet with an associated NAT Gateway
246 azure_rm_subnet:
247 resource_group: myResourceGroup
248 virtual_network_name: myVirtualNetwork
249 name: mySubnet
250 address_prefix_cidr: "10.1.0.0/16"
251 nat_gateway: myNatGateway
252
253 - name: Delete a subnet
254 azure_rm_subnet:
255 resource_group: myResourceGroup
256 virtual_network_name: myVirtualNetwork
257 name: mySubnet
258 state: absent
259 '''
260
261 RETURN = '''
262 state:
263 description:
264 - Current state of the subnet.
265 returned: success
266 type: complex
267 contains:
268 address_prefix:
269 description:
270 - IP address CIDR.
271 returned: always
272 type: str
273 sample: "10.1.0.0/16"
274 address_prefixes:
275 description:
276 - IP address for IPv4 and IPv6 CIDR.
277 returned: always
278 type: list
279 sample: ["10.2.0.0/24", "fdda:e69b:1587:495e::/64"]
280 id:
281 description:
282 - Subnet resource path.
283 returned: always
284 type: str
285 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVirtualNetwork/subnets/mySubnet"
286 name:
287 description:
288 - Subnet name.
289 returned: always
290 type: str
291 sample: "foobar"
292 network_security_group:
293 description:
294 - Associated network security group of subnets.
295 returned: always
296 type: complex
297 contains:
298 id:
299 description:
300 - Security group resource identifier.
301 returned: always
302 type: str
303 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/secgroupfoo"
304 name:
305 description:
306 - Name of the security group.
307 returned: always
308 type: str
309 sample: "secgroupfoo"
310 provisioning_state:
311 description:
312 - Success or failure of the provisioning event.
313 returned: always
314 type: str
315 sample: "Succeeded"
316 private_endpoint_network_policies:
317 description:
318 - C(Enabled) or C(Disabled) apply network policies on private endpoints in the subnet.
319 returned: always
320 type: str
321 sample: "Enabled"
322 private_link_service_network_policies:
323 description:
324 - C(Enabled) or C(Disabled) apply network policies on private link service in the subnet.
325 returned: always
326 type: str
327 sample: "Disabled"
328 default_outbound_access:
329 description:
330 - Set this property to false to disable default outbound connectivity for all VMs in the subnet.
331 type: bool
332 returned: always
333 sample: false
334 delegations:
335 description:
336 - Associated delegation of subnets
337 returned: always
338 type: list
339 contains:
340 name:
341 description:
342 - name of delegation
343 returned: when delegation is present
344 type: str
345 sample: "delegationname"
346 serviceName:
347 description:
348 - service associated to delegation
349 returned: when delegation is present
350 type: str
351 sample: "Microsoft.ContainerInstance/containerGroups"
352 actions:
353 description:
354 - list of actions associated with service of delegation
355 returned : when delegation is present
356 type: list
357 sample: ["Microsoft.Network/virtualNetworks/subnets/action"]
358 sharing_scope:
359 description:
360 - Set this property to Tenant to allow sharing subnet with other subscriptions in your AAD tenant.
361 type: str
362 returned: always
363 sample: None
364 service_endpoint_policies:
365 description:
366 - An array of service endpoint policies.
367 type: list
368 returned: always
369 sample: ["/subscriptions/xxx-xxx/resourceGroups/TestRG/providers/Microsoft.Network/serviceEndpointPolicies/testpolicy"]
370 ''' # NOQA
371
372 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase, CIDR_PATTERN, azure_id_to_dict, format_resource_id
373
374 try:
375 from azure.core.exceptions import ResourceNotFoundError
376 from azure.mgmt.core.tools import is_valid_resource_id
377 except ImportError:
378 # This is handled in azure_rm_common
379 pass
380
381
382 delegations_spec = dict(
383 name=dict(
384 type='str',
385 required=True
386 ),
387 serviceName=dict(
388 type='str',
389 required=True,
390 choices=['Microsoft.Web/serverFarms', 'Microsoft.ContainerInstance/containerGroups', 'Microsoft.Netapp/volumes',
391 'Microsoft.HardwareSecurityModules/dedicatedHSMs', 'Microsoft.ServiceFabricMesh/networks',
392 'Microsoft.Logic/integrationServiceEnvironments', 'Microsoft.Batch/batchAccounts', 'Microsoft.Sql/managedInstances',
393 'Microsoft.Web/hostingEnvironments', 'Microsoft.BareMetal/CrayServers', 'Microsoft.BareMetal/MonitoringServers',
394 'Microsoft.Databricks/workspaces', 'Microsoft.BareMetal/AzureHostedService', 'Microsoft.BareMetal/AzureVMware',
395 'Microsoft.BareMetal/AzureHPC', 'Microsoft.BareMetal/AzurePaymentHSM', 'Microsoft.StreamAnalytics/streamingJobs',
396 'Microsoft.DBforPostgreSQL/serversv2', 'Microsoft.AzureCosmosDB/clusters', 'Microsoft.MachineLearningServices/workspaces',
397 'Microsoft.DBforPostgreSQL/singleServers', 'Microsoft.DBforPostgreSQL/flexibleServers', 'Microsoft.DBforMySQL/serversv2',
398 'Microsoft.DBforMySQL/flexibleServers', 'Microsoft.ApiManagement/service', 'Microsoft.Synapse/workspaces',
399 'Microsoft.PowerPlatform/vnetaccesslinks', 'Microsoft.Network/managedResolvers', 'Microsoft.Kusto/clusters',
400 'Microsoft.ContainerService/managedClusters', 'Microsoft.App/environments',
401 'Microsoft.Network/applicationGateways']
402 ),
403 actions=dict(
404 type='list',
405 elements='str',
406 default=[]
407 )
408 )
409
410
411 def subnet_to_dict(subnet):
412 result = dict(
413 id=subnet.id,
414 name=subnet.name,
415 provisioning_state=subnet.provisioning_state,
416 address_prefix=subnet.address_prefix,
417 address_prefixes=subnet.address_prefixes,
418 network_security_group=dict(),
419 route_table=dict(),
420 private_endpoint_network_policies=subnet.private_endpoint_network_policies,
421 private_link_service_network_policies=subnet.private_link_service_network_policies,
422 nat_gateway=None,
423 sharing_scope=subnet.sharing_scope,
424 service_endpoint_policies=list(),
425 default_outbound_access=subnet.default_outbound_access
426 )
427 if subnet.network_security_group:
428 id_keys = azure_id_to_dict(subnet.network_security_group.id)
429 result['network_security_group']['id'] = subnet.network_security_group.id
430 result['network_security_group']['name'] = id_keys['networkSecurityGroups']
431 result['network_security_group']['resource_group'] = id_keys['resourceGroups']
432 if subnet.route_table:
433 id_keys = azure_id_to_dict(subnet.route_table.id)
434 result['route_table']['id'] = subnet.route_table.id
435 result['route_table']['name'] = id_keys['routeTables']
436 result['route_table']['resource_group'] = id_keys['resourceGroups']
437 if subnet.service_endpoints:
438 result['service_endpoints'] = [{'service': item.service, 'locations': item.locations or []} for item in subnet.service_endpoints]
439 if subnet.delegations:
440 result['delegations'] = [{'name': item.name, 'serviceName': item.service_name, 'actions': item.actions or []} for item in subnet.delegations]
441 if subnet.nat_gateway:
442 result['nat_gateway'] = subnet.nat_gateway.id
443 if subnet.service_endpoint_policies:
444 result['service_endpoint_policies'] = [item.id for item in subnet.service_endpoint_policies]
445 return result
446
447
448 class AzureRMSubnet(AzureRMModuleBase):
449
450 def __init__(self):
451
452 self.module_arg_spec = dict(
453 resource_group=dict(type='str', required=True),
454 name=dict(type='str', required=True),
455 state=dict(type='str', default='present', choices=['present', 'absent']),
456 virtual_network_name=dict(type='str', required=True, aliases=['virtual_network']),
457 address_prefix_cidr=dict(type='str', aliases=['address_prefix']),
458 address_prefixes_cidr=dict(type='list', aliases=['address_prefixes'], elements='str'),
459 default_outbound_access=dict(type='bool'),
460 security_group=dict(type='raw', aliases=['security_group_name']),
461 route_table=dict(type='raw'),
462 service_endpoints=dict(
463 type='list',
464 elements='dict',
465 options=dict(
466 service=dict(type='str', required=True),
467 locations=dict(type='list', elements='str')
468 )
469 ),
470 private_endpoint_network_policies=dict(
471 type='str',
472 default='Enabled',
473 choices=['Enabled', 'Disabled', 'NetworkSecurityGroupEnabled', 'RouteTableEnabled']
474 ),
475 private_link_service_network_policies=dict(
476 type='str',
477 default='Enabled',
478 choices=['Enabled', 'Disabled']
479 ),
480 delegations=dict(
481 type='list',
482 elements='dict',
483 options=delegations_spec
484 ),
485 nat_gateway=dict(type='str'),
486 sharing_scope=dict(type='str', choices=['DelegatedServices', 'Tenant']),
487 service_endpoint_policies=dict(
488 type='list',
489 elements='dict',
490 options=dict(
491 id=dict(type='str')
492 )
493 )
494 )
495
496 mutually_exclusive = [['address_prefix_cidr', 'address_prefixes_cidr']]
497
498 self.results = dict(
499 changed=False,
500 state=dict()
501 )
502
503 self.resource_group = None
504 self.name = None
505 self.state = None
506 self.virtual_network_name = None
507 self.address_prefix_cidr = None
508 self.address_prefixes_cidr = None
509 self.security_group = None
510 self.route_table = None
511 self.service_endpoints = None
512 self.private_link_service_network_policies = None
513 self.private_endpoint_network_policies = None
514 self.delegations = None
515 self.nat_gateway = None
516 self.service_endpoint_policies = None
517 self.sharing_scope = None
518 self.default_outbound_access = None
519
520 super(AzureRMSubnet, self).__init__(self.module_arg_spec,
521 supports_check_mode=True,
522 supports_tags=False)
523
524 def exec_module(self, **kwargs):
525
526 nsg = None
527 subnet = None
528
529 for key in self.module_arg_spec:
530 setattr(self, key, kwargs[key])
531
532 if self.delegations and len(self.delegations) > 1:
533 self.fail("Only one delegation is supported for a subnet")
534
535 if self.address_prefix_cidr and not CIDR_PATTERN.match(self.address_prefix_cidr):
536 self.fail("Invalid address_prefix_cidr value {0}".format(self.address_prefix_cidr))
537
538 nsg = dict()
539 if self.security_group:
540 nsg = self.parse_nsg()
541
542 nat_gateway = self.build_nat_gateway_id(self.nat_gateway)
543
544 route_table = dict()
545 if self.route_table:
546 route_table = self.parse_resource_to_dict(self.route_table)
547 self.route_table = format_resource_id(val=route_table['name'],
548 subscription_id=route_table['subscription_id'],
549 namespace='Microsoft.Network',
550 types='routeTables',
551 resource_group=route_table['resource_group'])
552
553 results = dict()
554 changed = False
555
556 try:
557 self.log('Fetching subnet {0}'.format(self.name))
558 subnet = self.network_client.subnets.get(self.resource_group,
559 self.virtual_network_name,
560 self.name)
561 self.check_provisioning_state(subnet, self.state)
562 results = subnet_to_dict(subnet)
563
564 if self.state == 'present':
565 if self.private_endpoint_network_policies is not None:
566 if results['private_endpoint_network_policies'] != self.private_endpoint_network_policies:
567 self.log("CHANGED: subnet {0} private_endpoint_network_policies".format(self.private_endpoint_network_policies))
568 changed = True
569 results['private_endpoint_network_policies'] = self.private_endpoint_network_policies
570 else:
571 subnet['private_endpoint_network_policies'] = results['private_endpoint_network_policies']
572 if self.private_link_service_network_policies is not None:
573 if results['private_link_service_network_policies'] != self.private_link_service_network_policies:
574 self.log("CHANGED: subnet {0} private_link_service_network_policies".format(self.private_link_service_network_policies))
575 changed = True
576 results['private_link_service_network_policies'] = self.private_link_service_network_policies
577 else:
578 subnet['private_link_service_network_policies'] = results['private_link_service_network_policies']
579
580 if self.address_prefix_cidr and results['address_prefix'] != self.address_prefix_cidr:
581 self.log("CHANGED: subnet {0} address_prefix_cidr".format(self.name))
582 changed = True
583 results['address_prefix'] = self.address_prefix_cidr
584 if self.address_prefixes_cidr and results['address_prefixes'] != self.address_prefixes_cidr:
585 self.log("CHANGED: subnet {0} address_prefixes_cidr".format(self.name))
586 changed = True
587 results['address_prefixes'] = self.address_prefixes_cidr
588
589 if self.security_group is not None and results['network_security_group'].get('id') != nsg.get('id'):
590 self.log("CHANGED: subnet {0} network security group".format(self.name))
591 changed = True
592 results['network_security_group']['id'] = nsg.get('id')
593 results['network_security_group']['name'] = nsg.get('name')
594 if self.route_table is not None:
595 if self.route_table != results['route_table'].get('id'):
596 changed = True
597 results['route_table']['id'] = self.route_table
598 self.log("CHANGED: subnet {0} route_table to {1}".format(self.name, route_table.get('name')))
599 else:
600 if results['route_table'].get('id') is not None:
601 changed = True
602 results['route_table']['id'] = None
603 self.log("CHANGED: subnet {0} will dissociate to route_table {1}".format(self.name, route_table.get('name')))
604
605 if self.service_endpoints or self.service_endpoints == []:
606 oldd = {}
607 for item in self.service_endpoints:
608 name = item['service']
609 locations = item.get('locations') or []
610 oldd[name] = {'service': name, 'locations': locations.sort()}
611 newd = {}
612 if 'service_endpoints' in results:
613 for item in results['service_endpoints']:
614 name = item['service']
615 locations = item.get('locations') or []
616 newd[name] = {'service': name, 'locations': locations.sort()}
617 if newd != oldd:
618 changed = True
619 results['service_endpoints'] = self.service_endpoints
620
621 if self.delegations:
622 oldde = {}
623 for item in self.delegations:
624 name = item['name']
625 serviceName = item['serviceName']
626 actions = item.get('actions') or []
627 oldde[name] = {'name': name, 'serviceName': serviceName, 'actions': actions.sort()}
628 newde = {}
629 if 'delegations' in results:
630 for item in results['delegations']:
631 name = item['name']
632 serviceName = item['serviceName']
633 actions = item.get('actions') or []
634 newde[name] = {'name': name, 'serviceName': serviceName, 'actions': actions.sort()}
635 if newde != oldde:
636 changed = True
637 results['delegations'] = self.delegations
638
639 if nat_gateway is not None:
640 if nat_gateway != results['nat_gateway']:
641 changed = True
642 # Update associated NAT Gateway
643 results['nat_gateway'] = nat_gateway
644 else:
645 if results['nat_gateway'] is not None:
646 changed = True
647 # Disassociate NAT Gateway
648 results['nat_gateway'] = None
649 if self.default_outbound_access is not None and bool(self.default_outbound_access != results.get('default_outbound_access')):
650 changed = True
651 else:
652 self.default_outbound_access = results.get('default_outbound_access')
653
654 if self.sharing_scope and self.sharing_scope != results['sharing_scope']:
655 changed = True
656 else:
657 results['sharing_scope'] = results['sharing_scope']
658 if self.service_endpoint_policies:
659 new_policies = [dict(id=item) for item in results['service_endpoint_policies']]
660 for item in self.service_endpoint_policies:
661 if item['id'] not in results['service_endpoint_policies']:
662 new_policies.append(item)
663 changed = True
664 self.service_endpoint_policies = new_policies
665 else:
666 self.service_endpoint_policies = results['service_endpoint_policies'] if results['service_endpoint_policies'] else None
667
668 elif self.state == 'absent':
669 changed = True
670 except ResourceNotFoundError:
671 # the subnet does not exist
672 if self.state == 'present':
673 changed = True
674
675 self.results['changed'] = changed
676 self.results['state'] = results
677
678 if not self.check_mode:
679
680 if self.state == 'present' and changed:
681 if not subnet:
682 # create new subnet
683 if not self.address_prefix_cidr and not self.address_prefixes_cidr:
684 self.fail('address_prefix_cidr or address_prefixes_cidr is not set')
685 self.log('Creating subnet {0}'.format(self.name))
686 subnet = self.network_models.Subnet(
687 address_prefix=self.address_prefix_cidr,
688 address_prefixes=self.address_prefixes_cidr
689 )
690 if nsg:
691 subnet.network_security_group = self.network_models.NetworkSecurityGroup(id=nsg.get('id'))
692 if self.route_table:
693 subnet.route_table = self.network_models.RouteTable(id=self.route_table)
694 if self.service_endpoints:
695 subnet.service_endpoints = self.service_endpoints
696 if self.private_endpoint_network_policies:
697 subnet.private_endpoint_network_policies = self.private_endpoint_network_policies
698 if self.private_link_service_network_policies:
699 subnet.private_link_service_network_policies = self.private_link_service_network_policies
700 if self.delegations:
701 subnet.delegations = self.delegations
702 if nat_gateway:
703 subnet.nat_gateway = self.network_models.SubResource(id=nat_gateway)
704 if self.sharing_scope:
705 subnet.sharing_scope = self.sharing_scope
706 if self.service_endpoint_policies:
707 subnet.service_endpoint_policies = self.service_endpoint_policies
708 else:
709 # update subnet
710 self.log('Updating subnet {0}'.format(self.name))
711 subnet = self.network_models.Subnet(
712 address_prefix=results['address_prefix'],
713 address_prefixes=results['address_prefixes']
714 )
715 if results['network_security_group'].get('id') is not None:
716 subnet.network_security_group = self.network_models.NetworkSecurityGroup(id=results['network_security_group'].get('id'))
717 if results['route_table'].get('id') is not None:
718 subnet.route_table = self.network_models.RouteTable(id=results['route_table'].get('id'))
719
720 if results.get('service_endpoints') is not None:
721 subnet.service_endpoints = results['service_endpoints']
722 if results.get('private_link_service_network_policies') is not None:
723 subnet.private_link_service_network_policies = results['private_link_service_network_policies']
724 if results.get('private_endpoint_network_policies') is not None:
725 subnet.private_endpoint_network_policies = results['private_endpoint_network_policies']
726 if results.get('delegations') is not None:
727 subnet.delegations = results['delegations']
728 if results.get('nat_gateway') is not None:
729 subnet.nat_gateway = self.network_models.SubResource(id=results['nat_gateway'])
730 if self.sharing_scope:
731 subnet.sharing_scope = self.sharing_scope
732 if self.service_endpoint_policies:
733 subnet.service_endpoint_policies = self.service_endpoint_policies
734
735 subnet.default_outbound_access = self.default_outbound_access
736 self.results['state'] = self.create_or_update_subnet(subnet)
737 elif self.state == 'absent' and changed:
738 # delete subnet
739 self.delete_subnet()
740 # the delete does not actually return anything. if no exception, then we'll assume
741 # it worked.
742 self.results['state']['status'] = 'Deleted'
743
744 return self.results
745
746 def create_or_update_subnet(self, subnet):
747 try:
748 poller = self.network_client.subnets.begin_create_or_update(self.resource_group,
749 self.virtual_network_name,
750 self.name,
751 subnet)
752 new_subnet = self.get_poller_result(poller)
753 except Exception as exc:
754 self.fail("Error creating or updating subnet {0} - {1}".format(self.name, str(exc)))
755 self.check_provisioning_state(new_subnet)
756 return subnet_to_dict(new_subnet)
757
758 def delete_subnet(self):
759 self.log('Deleting subnet {0}'.format(self.name))
760 try:
761 poller = self.network_client.subnets.begin_delete(self.resource_group,
762 self.virtual_network_name,
763 self.name)
764 result = self.get_poller_result(poller)
765 except Exception as exc:
766 self.fail("Error deleting subnet {0} - {1}".format(self.name, str(exc)))
767
768 return result
769
770 def parse_nsg(self):
771 nsg = self.security_group
772 resource_group = self.resource_group
773 if isinstance(self.security_group, dict):
774 nsg = self.security_group.get('name')
775 resource_group = self.security_group.get('resource_group', self.resource_group)
776 id = format_resource_id(val=nsg,
777 subscription_id=self.subscription_id,
778 namespace='Microsoft.Network',
779 types='networkSecurityGroups',
780 resource_group=resource_group)
781 name = azure_id_to_dict(id).get('name')
782 return dict(id=id, name=name)
783
784 def build_nat_gateway_id(self, resource):
785 """
786 Common method to build a resource id from different inputs
787 """
788 if resource is None:
789 return None
790 if is_valid_resource_id(resource):
791 return resource
792 resource_dict = self.parse_resource_to_dict(resource)
793 return format_resource_id(val=resource_dict['name'],
794 subscription_id=resource_dict.get('subscription_id'),
795 namespace='Microsoft.Network',
796 types='natGateways',
797 resource_group=resource_dict.get('resource_group'))
798
799
800 def main():
801 AzureRMSubnet()
802
803
804 if __name__ == '__main__':
805 main()