Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016 Matt Davis, <[email protected]>
4 # Chris Houseknecht, <[email protected]>
5 # Yuwei ZHou, <[email protected]>
6 #
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = '''
14 ---
15 module: azure_rm_networkinterface
16
17 version_added: "0.1.0"
18
19 short_description: Manage Azure network interfaces
20
21 description:
22 - Create, update or delete a network interface.
23 - When creating a network interface you must provide the name of an existing virtual network, the name of an existing subnet within the virtual network.
24 - A default security group and public IP address will be created automatically.
25 - Or you can provide the name of an existing security group and public IP address.
26 - See the examples below for more details.
27
28 options:
29 resource_group:
30 description:
31 - Name of a resource group where the network interface exists or will be created.
32 required: true
33 type: str
34 name:
35 description:
36 - Name of the network interface.
37 required: true
38 type: str
39 state:
40 description:
41 - Assert the state of the network interface. Use C(present) to create or update an interface and
42 C(absent) to delete an interface.
43 default: present
44 type: str
45 choices:
46 - absent
47 - present
48 location:
49 description:
50 - Valid Azure location. Defaults to location of the resource group.
51 type: str
52 virtual_network:
53 description:
54 - An existing virtual network with which the network interface will be associated. Required when creating a network interface.
55 - It can be the virtual network's name.
56 - Make sure your virtual network is in the same resource group as NIC when you give only the name.
57 - It can be the virtual network's resource id.
58 - It can be a dict which contains I(name) and I(resource_group) of the virtual network.
59 - Required when creating.
60 type: raw
61 aliases:
62 - virtual_network_name
63 subnet_name:
64 description:
65 - Name of an existing subnet within the specified virtual network. Required when creating a network interface.
66 - Use the C(virtual_network)'s resource group.
67 - Required when creating.
68 aliases:
69 - subnet
70 type: str
71 os_type:
72 description:
73 - Determines any rules to be added to a default security group.
74 - When creating a network interface, if no security group name is provided, a default security group will be created.
75 - If the I(os_type=Windows), a rule allowing RDP access will be added.
76 - If the I(os_type=Linux), a rule allowing SSH access will be added.
77 type: str
78 choices:
79 - Windows
80 - Linux
81 - windows
82 - linux
83 default: Linux
84 ip_configurations:
85 description:
86 - List of IP configurations. Each configuration object should include
87 field I(private_ip_address), I(private_ip_allocation_method), I(public_ip_address_name), I(public_ip), I(public_ip_allocation_method), I(name).
88 type: list
89 elements: dict
90 default: []
91 suboptions:
92 name:
93 description:
94 - Name of the IP configuration.
95 required: true
96 type: str
97 private_ip_address:
98 description:
99 - Private IP address for the IP configuration.
100 type: str
101 private_ip_address_version:
102 description:
103 - The version of the IP configuration.
104 type: str
105 choices:
106 - IPv4
107 - IPv6
108 default: IPv4
109 private_ip_allocation_method:
110 description:
111 - Private IP allocation method.
112 type: str
113 choices:
114 - Dynamic
115 - Static
116 default: Dynamic
117 public_ip_address_name:
118 description:
119 - Name of the public IP address. None for disable IP address.
120 type: str
121 aliases:
122 - public_ip_address
123 - public_ip_name
124 public_ip_allocation_method:
125 description:
126 - Public IP allocation method.
127 type: str
128 choices:
129 - Dynamic
130 - Static
131 default: Dynamic
132 load_balancer_backend_address_pools:
133 description:
134 - List of existing load-balancer backend address pools to associate with the network interface.
135 - Can be written as a resource ID.
136 - Also can be a dict of I(name) and I(load_balancer).
137 type: list
138 elements: raw
139 application_gateway_backend_address_pools:
140 description:
141 - List of existing application gateway backend address pools to associate with the network interface.
142 - Can be written as a resource ID.
143 - Also can be a dict of I(name) and I(application_gateway).
144 type: list
145 elements: raw
146 version_added: "1.10.0"
147 primary:
148 description:
149 - Whether the IP configuration is the primary one in the list.
150 - The first IP configuration default set to I(primary=True).
151 type: bool
152 default: False
153 application_security_groups:
154 description:
155 - List of application security groups in which the IP configuration is included.
156 - Element of the list could be a resource id of application security group, or the name of the application
157 security group located in the current resource group, or a dictionary with resource groups and names.
158 type: list
159 elements: raw
160 enable_accelerated_networking:
161 description:
162 - Whether the network interface should be created with the accelerated networking feature or not.
163 type: bool
164 default: False
165 create_with_security_group:
166 description:
167 - Whether a security group should be be created with the NIC.
168 - If this flag set to C(True) and no I(security_group) set, a default security group will be created.
169 type: bool
170 default: True
171 security_group:
172 description:
173 - An existing security group with which to associate the network interface.
174 - If not provided, a default security group will be created when I(create_with_security_group=true).
175 - It can be the name of security group.
176 - Make sure the security group is in the same resource group when you only give its name.
177 - It can be the resource id.
178 - It can be a dict contains security_group's I(name) and I(resource_group).
179 aliases:
180 - security_group_name
181 type: raw
182 open_ports:
183 description:
184 - When a default security group is created for a Linux host a rule will be added allowing inbound TCP
185 connections to the default SSH port C(22), and for a Windows host rules will be added allowing inbound
186 access to RDP ports C(3389) and C(5986). Override the default ports by providing a list of open ports.
187 type: list
188 elements: str
189 enable_ip_forwarding:
190 description:
191 - Whether to enable IP forwarding.
192 aliases:
193 - ip_forwarding
194 type: bool
195 default: False
196 dns_servers:
197 description:
198 - Which DNS servers should the NIC lookup.
199 - List of IP addresses.
200 type: list
201 elements: str
202 extends_documentation_fragment:
203 - azure.azcollection.azure
204 - azure.azcollection.azure_tags
205
206 author:
207 - Chris Houseknecht (@chouseknecht)
208 - Matt Davis (@nitzmahone)
209 - Yuwei Zhou (@yuwzho)
210 '''
211
212 EXAMPLES = '''
213 - name: Create a network interface with minimal parameters
214 azure_rm_networkinterface:
215 name: nic001
216 resource_group: myResourceGroup
217 virtual_network: vnet001
218 subnet_name: subnet001
219 ip_configurations:
220 - name: ipconfig1
221 public_ip_address_name: publicip001
222 primary: true
223
224 - name: Create a network interface with private IP address only (no Public IP)
225 azure_rm_networkinterface:
226 name: nic001
227 resource_group: myResourceGroup
228 virtual_network: vnet001
229 subnet_name: subnet001
230 create_with_security_group: false
231 ip_configurations:
232 - name: ipconfig1
233 primary: true
234
235 - name: Create a network interface for use in a Windows host (opens RDP port) with custom RDP port
236 azure_rm_networkinterface:
237 name: nic002
238 resource_group: myResourceGroup
239 virtual_network: vnet001
240 subnet_name: subnet001
241 os_type: Windows
242 rdp_port: 3399
243 security_group: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurit
244 yGroups/nsg001"
245 ip_configurations:
246 - name: ipconfig1
247 public_ip_address_name: publicip001
248 primary: true
249
250 - name: Create a network interface using existing security group and public IP
251 azure_rm_networkinterface:
252 name: nic003
253 resource_group: myResourceGroup
254 virtual_network: vnet001
255 subnet_name: subnet001
256 security_group: secgroup001
257 ip_configurations:
258 - name: ipconfig1
259 public_ip_address_name: publicip001
260 primary: true
261
262 - name: Create a network with multiple ip configurations
263 azure_rm_networkinterface:
264 name: nic004
265 resource_group: myResourceGroup
266 subnet_name: subnet001
267 virtual_network: vnet001
268 security_group:
269 name: testnic002
270 resource_group: Testing1
271 ip_configurations:
272 - name: ipconfig1
273 public_ip_address_name: publicip001
274 primary: true
275 - name: ipconfig2
276 load_balancer_backend_address_pools:
277 - "{{ loadbalancer001.state.backend_address_pools[0].id }}"
278 - name: backendaddrpool1
279 load_balancer: loadbalancer001
280
281 - name: Create network interface attached to application gateway backend address pool
282 azure_rm_networkinterface:
283 name: nic-appgw
284 resource_group: myResourceGroup
285 virtual_network: vnet001
286 subnet_name: subnet001
287 create_with_security_group: false
288 ip_configurations:
289 - name: default
290 primary: true
291 application_gateway_backend_address_pools:
292 - name: myApplicationGatewayBackendAddressPool
293 application_gateway: myApplicationGateway
294
295 - name: Create a network interface in accelerated networking mode
296 azure_rm_networkinterface:
297 name: nic005
298 resource_group: myResourceGroup
299 virtual_network_name: vnet001
300 subnet_name: subnet001
301 enable_accelerated_networking: true
302
303 - name: Create a network interface with IP forwarding
304 azure_rm_networkinterface:
305 name: nic001
306 resource_group: myResourceGroup
307 virtual_network: vnet001
308 subnet_name: subnet001
309 ip_forwarding: true
310 ip_configurations:
311 - name: ipconfig1
312 public_ip_address_name: publicip001
313 primary: true
314
315 - name: Create a network interface with dns servers
316 azure_rm_networkinterface:
317 name: nic009
318 resource_group: myResourceGroup
319 virtual_network: vnet001
320 subnet_name: subnet001
321 dns_servers:
322 - 8.8.8.8
323
324 - name: Delete network interface
325 azure_rm_networkinterface:
326 resource_group: myResourceGroup
327 name: nic003
328 state: absent
329 '''
330
331 RETURN = '''
332 state:
333 description:
334 - The current state of the network interface.
335 returned: always
336 type: complex
337 contains:
338 dns_server:
339 description:
340 - Which DNS servers should the NIC lookup.
341 - List of IP addresses.
342 type: list
343 sample: ['8.9.10.11', '7.8.9.10']
344 dns_setting:
345 description:
346 - The DNS settings in network interface.
347 type: dict
348 sample: {
349 "applied_dns_servers": [],
350 "dns_servers": [
351 "8.9.10.11",
352 "7.8.9.10"
353 ],
354 "internal_dns_name_label": null,
355 "internal_fqdn": null
356 }
357 enable_ip_forwarding:
358 description:
359 Whether to enable IP forwarding.
360 type: bool
361 sample: true
362 etag:
363 description:
364 - A unique read-only string that changes whenever the resource is updated.
365 type: str
366 sample: 'W/"be115a43-2148-4545-a324-f33ad444c926"'
367 id:
368 description:
369 - Id of the network interface.
370 type: str
371 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nic003"
372 enable_accelerated_networking:
373 description:
374 - Whether the network interface should be created with the accelerated networking feature or not.
375 type: bool
376 sample: true
377 ip_configurations:
378 description:
379 - List of IP configurations.
380 type: complex
381 contains:
382 name:
383 description:
384 - Name of the IP configuration.
385 type: str
386 sample: default
387 load_balancer_backend_address_pools:
388 description:
389 - List of existing load-balancer backend address pools associated with the network interface.
390 type: list
391 application_gateway_backend_address_pools:
392 description:
393 - List of existing application gateway backend address pool resource IDs associated with the network interface.
394 type: list
395 version_added: "1.10.0"
396 sample: ["/subscriptions/xxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/applicationGateways/myGateway/
397 backendAddressPools/myBackendAddressPool"]
398 private_ip_address:
399 description:
400 - Private IP address for the IP configuration.
401 type: str
402 sample: "10.1.0.10"
403 private_ip_address_version:
404 description:
405 - The version of the IP configuration.
406 type: str
407 sample: "IPv4"
408 private_ip_allocation_method:
409 description:
410 - Private IP allocation method.
411 type: str
412 sample: "Static"
413 public_ip_address:
414 description:
415 - Name of the public IP address. None for disable IP address.
416 type: dict
417 sample: {
418 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/publicIPAddresse
419 s/publicip001",
420 "name": "publicip001"
421 }
422 subnet:
423 description:
424 - The reference of the subnet resource.
425 type: dict
426 sample: {
427 "id": "/subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/
428 myresourcegroup/providers/Microsoft.Network/virtualNetworks/tnb57dc95318/subnets/tnb57dc95318",
429 "name": "tnb57dc95318",
430 "resource_group": "myresourcegroup",
431 "virtual_network_name": "tnb57dc95318"
432 }
433 location:
434 description:
435 - The network interface resource location.
436 type: str
437 sample: eastus
438 mac_address:
439 description:
440 - The MAC address of the network interface.
441 type: str
442 name:
443 description:
444 - Name of the network interface.
445 type: str
446 sample: nic003
447 network_security_group:
448 description:
449 - The reference of the network security group resource.
450 type: dict
451 sample: {
452 "id": "/subscriptions//xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/
453 myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/nsg001",
454 "name": "nsg001"
455 }
456 primary:
457 description:
458 - Get whether this is a primary network interface on virtual machine.
459 type: bool
460 sample: true
461 provisioning_state:
462 description:
463 - The provisioning state of the public IP resource.
464 type: str
465 sample: Succeeded
466 tags:
467 description:
468 -Tags of the network interface.
469 type: dict
470 sample: { 'key': 'value' }
471 type:
472 description:
473 - Type of the resource.
474 type: str
475 sample: "Microsoft.Network/networkInterfaces"
476 '''
477
478 try:
479 from azure.mgmt.core.tools import resource_id, is_valid_resource_id
480 from azure.core.exceptions import ResourceNotFoundError
481 except ImportError:
482 # This is handled in azure_rm_common
483 pass
484
485 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
486 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import (azure_id_to_dict,
487 normalize_location_name,
488 format_resource_id
489 )
490 from ansible.module_utils._text import to_native
491
492
493 def subnet_to_dict(subnet):
494 dic = azure_id_to_dict(subnet.id)
495 return dict(
496 id=subnet.id,
497 virtual_network_name=dic.get('virtualNetworks'),
498 resource_group=dic.get('resourceGroups'),
499 name=dic.get('subnets')
500 )
501
502
503 def nic_to_dict(nic):
504 ip_configurations = [
505 dict(
506 name=config.name,
507 private_ip_address=config.private_ip_address,
508 private_ip_address_version=config.private_ip_address_version,
509 private_ip_allocation_method=config.private_ip_allocation_method,
510 subnet=subnet_to_dict(config.subnet),
511 primary=config.primary if config.primary else False,
512 load_balancer_backend_address_pools=([item.id for item in config.load_balancer_backend_address_pools]
513 if config.load_balancer_backend_address_pools else None),
514 application_gateway_backend_address_pools=([item.id for item in config.application_gateway_backend_address_pools]
515 if config.application_gateway_backend_address_pools else None),
516 public_ip_address=dict(
517 id=config.public_ip_address.id,
518 name=azure_id_to_dict(config.public_ip_address.id).get('publicIPAddresses'),
519 public_ip_allocation_method=config.public_ip_address.public_ip_allocation_method
520 ) if config.public_ip_address else None,
521 application_security_groups=([asg.id for asg in config.application_security_groups]
522 if config.application_security_groups else None)
523 ) for config in nic.ip_configurations
524 ]
525 return dict(
526 id=nic.id,
527 name=nic.name,
528 type=nic.type,
529 location=nic.location,
530 tags=nic.tags,
531 network_security_group=dict(
532 id=nic.network_security_group.id,
533 name=azure_id_to_dict(nic.network_security_group.id).get('networkSecurityGroups')
534 ) if nic.network_security_group else None,
535 dns_settings=dict(
536 dns_servers=nic.dns_settings.dns_servers,
537 applied_dns_servers=nic.dns_settings.applied_dns_servers,
538 internal_dns_name_label=nic.dns_settings.internal_dns_name_label,
539 internal_fqdn=nic.dns_settings.internal_fqdn
540 ),
541 ip_configurations=ip_configurations,
542 ip_configuration=ip_configurations[0] if len(ip_configurations) == 1 else None, # for compatible issue, keep this field
543 mac_address=nic.mac_address,
544 enable_ip_forwarding=nic.enable_ip_forwarding,
545 provisioning_state=nic.provisioning_state,
546 etag=nic.etag,
547 enable_accelerated_networking=nic.enable_accelerated_networking,
548 dns_servers=nic.dns_settings.dns_servers,
549 )
550
551
552 ip_configuration_spec = dict(
553 name=dict(type='str', required=True),
554 private_ip_address=dict(type='str'),
555 private_ip_address_version=dict(type='str', choices=['IPv4', 'IPv6'], default='IPv4'),
556 private_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static'], default='Dynamic'),
557 public_ip_address_name=dict(type='str', aliases=['public_ip_address', 'public_ip_name']),
558 public_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static'], default='Dynamic'),
559 load_balancer_backend_address_pools=dict(type='list', elements='raw'),
560 application_gateway_backend_address_pools=dict(type='list', elements='raw'),
561 primary=dict(type='bool', default=False),
562 application_security_groups=dict(type='list', elements='raw')
563 )
564
565
566 class AzureRMNetworkInterface(AzureRMModuleBaseExt):
567
568 def __init__(self):
569
570 self.module_arg_spec = dict(
571 resource_group=dict(type='str', required=True),
572 name=dict(type='str', required=True),
573 location=dict(type='str'),
574 enable_accelerated_networking=dict(type='bool', default=False),
575 create_with_security_group=dict(type='bool', default=True),
576 security_group=dict(type='raw', aliases=['security_group_name']),
577 state=dict(default='present', choices=['present', 'absent']),
578 subnet_name=dict(type='str', aliases=['subnet']),
579 virtual_network=dict(type='raw', aliases=['virtual_network_name']),
580 ip_configurations=dict(type='list', default=[], elements='dict', options=ip_configuration_spec),
581 os_type=dict(type='str', choices=['Windows', 'Linux', 'windows', 'linux'], default='Linux'),
582 open_ports=dict(type='list', elements='str'),
583 enable_ip_forwarding=dict(type='bool', aliases=['ip_forwarding'], default=False),
584 dns_servers=dict(type='list', elements='str'),
585 )
586
587 self.resource_group = None
588 self.name = None
589 self.location = None
590 self.create_with_security_group = None
591 self.enable_accelerated_networking = None
592 self.security_group = None
593 self.subnet_name = None
594 self.virtual_network = None
595 self.state = None
596 self.tags = None
597 self.os_type = None
598 self.open_ports = None
599 self.enable_ip_forwarding = None
600 self.ip_configurations = None
601 self.dns_servers = None
602
603 self.results = dict(
604 changed=False,
605 state=dict(),
606 )
607
608 super(AzureRMNetworkInterface, self).__init__(derived_arg_spec=self.module_arg_spec,
609 supports_check_mode=True)
610
611 def exec_module(self, **kwargs):
612
613 for key in list(self.module_arg_spec.keys()) + ['tags']:
614 setattr(self, key, kwargs[key])
615
616 results = None
617 changed = False
618 nic = None
619 nsg = None
620
621 resource_group = self.get_resource_group(self.resource_group)
622 if not self.location:
623 # Set default location
624 self.location = resource_group.location
625 self.location = normalize_location_name(self.location)
626
627 # if not set the security group name, use nic name for default
628 self.security_group = self.parse_resource_to_dict(self.security_group or self.name)
629
630 # if application security groups set, convert to resource id format
631 primary_flag = False
632 if self.ip_configurations:
633 for config in self.ip_configurations:
634 if config.get('primary'):
635 primary_flag = True
636 if config.get('application_security_groups'):
637 asgs = []
638 for asg in config['application_security_groups']:
639 asg_resource_id = asg
640 if isinstance(asg, str):
641 if is_valid_resource_id(asg):
642 asg = self.parse_resource_to_dict(asg)
643 else:
644 asg = dict(name=asg)
645 else:
646 if asg.get('name') is None:
647 self.fail("If the element of application_security_groups is a dictionary, you must define 'name'.")
648 asg_resource_id = format_resource_id(val=asg['name'],
649 subscription_id=asg.get('subscription_id', self.subscription_id),
650 namespace='Microsoft.Network',
651 types='applicationSecurityGroups',
652 resource_group=asg.get('resource_group', self.resource_group))
653 asgs.append(asg_resource_id)
654 if len(asgs) > 0:
655 config['application_security_groups'] = asgs
656 if not primary_flag:
657 self.ip_configurations[0]['primary'] = True
658
659 # If ip_confiurations is not specified then provide the default
660 # private interface
661 skip_compare = False
662 if self.state == 'present' and not self.ip_configurations:
663 skip_compare = True
664 self.ip_configurations = [
665 dict(
666 name='default',
667 private_ip_allocation_method='Dynamic',
668 primary=True
669 )
670 ]
671
672 try:
673 self.log('Fetching network interface {0}'.format(self.name))
674 nic = self.network_client.network_interfaces.get(self.resource_group, self.name)
675
676 self.log('Network interface {0} exists'.format(self.name))
677 self.check_provisioning_state(nic, self.state)
678 results = nic_to_dict(nic)
679 self.log(results, pretty_print=True)
680
681 nsg = None
682 if self.state == 'present':
683 # check for update
684 update_tags, self.tags = self.update_tags(results['tags'])
685 if update_tags:
686 changed = True
687
688 if self.create_with_security_group != bool(results.get('network_security_group')):
689 self.log("CHANGED: add or remove network interface {0} network security group".format(self.name))
690 changed = True
691
692 if self.enable_accelerated_networking != bool(results.get('enable_accelerated_networking')):
693 self.log("CHANGED: Accelerated Networking set to {0} (previously {1})".format(
694 self.enable_accelerated_networking,
695 results.get('enable_accelerated_networking')))
696 changed = True
697
698 if self.enable_ip_forwarding != bool(results.get('enable_ip_forwarding')):
699 self.log("CHANGED: IP forwarding set to {0} (previously {1})".format(
700 self.enable_ip_forwarding,
701 results.get('enable_ip_forwarding')))
702 changed = True
703
704 # We need to ensure that dns_servers are list like
705 dns_servers_res = results.get('dns_settings').get('dns_servers')
706 _dns_servers_set = sorted(self.dns_servers) if isinstance(self.dns_servers, list) else list()
707 _dns_servers_res = sorted(dns_servers_res) if isinstance(self.dns_servers, list) else list()
708 if _dns_servers_set != _dns_servers_res:
709 self.log("CHANGED: DNS servers set to {0} (previously {1})".format(
710 ", ".join(_dns_servers_set),
711 ", ".join(_dns_servers_res)))
712 changed = True
713
714 if not changed:
715 nsg = self.get_security_group(self.security_group['resource_group'], self.security_group['name'])
716 if nsg and results.get('network_security_group') and results['network_security_group'].get('id') != nsg.id:
717 self.log("CHANGED: network interface {0} network security group".format(self.name))
718 changed = True
719
720 if self.virtual_network is None:
721 self.virtual_network = dict(resource_group=results['ip_configurations'][0]['subnet']['resource_group'],
722 subscription_id=self.parse_resource_to_dict(results['ip_configurations'][0]['subnet']['id'])['subscription_id'],
723 name=results['ip_configurations'][0]['subnet']['virtual_network_name'])
724 else:
725 # parse the virtual network resource group and name
726 self.virtual_network = self.parse_resource_to_dict(self.virtual_network)
727
728 if self.subnet_name is None:
729 self.subnet_name = results['ip_configurations'][0]['subnet']['name']
730
731 if results['ip_configurations'][0]['subnet']['virtual_network_name'] != self.virtual_network['name']:
732 self.log("CHANGED: network interface {0} virtual network name".format(self.name))
733 changed = True
734
735 if results['ip_configurations'][0]['subnet']['resource_group'] != self.virtual_network['resource_group']:
736 self.log("CHANGED: network interface {0} virtual network resource group".format(self.name))
737 changed = True
738
739 if results['ip_configurations'][0]['subnet']['name'] != self.subnet_name:
740 self.log("CHANGED: network interface {0} subnet name".format(self.name))
741 changed = True
742
743 # check the ip_configuration is changed
744 # construct two set with the same structure and then compare
745 # the list should contains:
746 # name, private_ip_address, public_ip_address_name, private_ip_allocation_method, subnet_name
747 ip_configuration_result = self.construct_ip_configuration_set(results['ip_configurations'])
748 ip_configuration_request = self.construct_ip_configuration_set(self.ip_configurations)
749 if skip_compare:
750 self.ip_configurations = results['ip_configurations']
751 else:
752 if not primary_flag:
753 self.ip_configurations[0]['primary'] = False
754 if not self.default_compare({}, ip_configuration_request, ip_configuration_result, '', dict(compare=[])):
755 changed = True
756 ip_configuration_request_name = [item['name'] for item in ip_configuration_request]
757 for item_result in results['ip_configurations']:
758 if item_result['name'] not in ip_configuration_request_name:
759 if primary_flag and item_result.get('primary'):
760 self.fail("Both the service and playbook ip configuration have primary keys. Please confirm which primary key is used")
761 self.ip_configurations.append(item_result)
762
763 elif self.state == 'absent':
764 self.log("CHANGED: network interface {0} exists but requested state is 'absent'".format(self.name))
765 changed = True
766 except ResourceNotFoundError:
767 self.log('Network interface {0} does not exist'.format(self.name))
768 if self.state == 'present':
769 self.log("CHANGED: network interface {0} does not exist but requested state is 'present'".format(self.name))
770 changed = True
771 if self.virtual_network is None or self.subnet_name is None:
772 self.fail("Required configure 'virtual_network' and 'subnet_name' when creating a new NIC.")
773 else:
774 # parse the virtual network resource group and name
775 self.virtual_network = self.parse_resource_to_dict(self.virtual_network)
776
777 self.results['changed'] = changed
778 self.results['state'] = results
779
780 if self.check_mode:
781 return self.results
782
783 if changed:
784 if self.state == 'present':
785 subnet = self.network_models.SubResource(
786 id='/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/virtualNetworks/{2}/subnets/{3}'.format(
787 self.virtual_network['subscription'] if self.virtual_network.get('subscription') else self.virtual_network['subscription_id'],
788 self.virtual_network['resource_group'],
789 self.virtual_network['name'],
790 self.subnet_name))
791
792 nic_ip_configurations = [
793 self.network_models.NetworkInterfaceIPConfiguration(
794 private_ip_allocation_method=ip_config.get('private_ip_allocation_method'),
795 private_ip_address=ip_config.get('private_ip_address'),
796 private_ip_address_version=ip_config.get('private_ip_address_version'),
797 name=ip_config.get('name'),
798 subnet=subnet,
799 public_ip_address=self.get_or_create_public_ip_address(ip_config),
800 load_balancer_backend_address_pools=([self.network_models.BackendAddressPool(id=self.backend_addr_pool_id(bap_id))
801 for bap_id in ip_config.get('load_balancer_backend_address_pools')]
802 if ip_config.get('load_balancer_backend_address_pools') else None),
803 application_gateway_backend_address_pools=([self.network_models.ApplicationGatewayBackendAddressPool
804 (id=self.gateway_backend_addr_pool_id(bap_id))
805 for bap_id in ip_config.get('application_gateway_backend_address_pools')]
806 if ip_config.get('application_gateway_backend_address_pools') else None),
807 primary=ip_config.get('primary'),
808 application_security_groups=([self.network_models.ApplicationSecurityGroup(id=asg_id)
809 for asg_id in ip_config.get('application_security_groups')]
810 if ip_config.get('application_security_groups') else None)
811 ) for ip_config in self.ip_configurations
812 ]
813
814 nsg = self.create_default_securitygroup(self.security_group['resource_group'],
815 self.location,
816 self.security_group['name'],
817 self.os_type,
818 self.open_ports) if self.create_with_security_group else None
819
820 self.log('Creating or updating network interface {0}'.format(self.name))
821 nic = self.network_models.NetworkInterface(
822 id=results['id'] if results else None,
823 location=self.location,
824 tags=self.tags,
825 ip_configurations=nic_ip_configurations,
826 enable_accelerated_networking=self.enable_accelerated_networking,
827 enable_ip_forwarding=self.enable_ip_forwarding,
828 network_security_group=nsg
829 )
830 if self.dns_servers:
831 dns_settings = self.network_models.NetworkInterfaceDnsSettings(
832 dns_servers=self.dns_servers)
833 nic.dns_settings = dns_settings
834 self.results['state'] = self.create_or_update_nic(nic)
835 elif self.state == 'absent':
836 self.log('Deleting network interface {0}'.format(self.name))
837 self.delete_nic()
838 # Delete doesn't return anything. If we get this far, assume success
839 self.results['state']['status'] = 'Deleted'
840
841 return self.results
842
843 def get_or_create_public_ip_address(self, ip_config):
844 if 'public_ip_address' in ip_config and ip_config.get('public_ip_address') is not None:
845 name = ip_config['public_ip_address'].get('name')
846 else:
847 name = ip_config.get('public_ip_address_name')
848
849 if not name:
850 return None
851
852 pip = self.get_public_ip_address(name)
853 if not pip:
854 params = self.network_models.PublicIPAddress(
855 location=self.location,
856 public_ip_allocation_method=ip_config.get('public_ip_allocation_method'),
857 )
858 try:
859 poller = self.network_client.public_ip_addresses.begin_create_or_update(self.resource_group, name, params)
860 pip = self.get_poller_result(poller)
861 except Exception as exc:
862 self.fail("Error creating {0} - {1}".format(name, str(exc)))
863 return pip
864
865 def create_or_update_nic(self, nic):
866 try:
867 poller = self.network_client.network_interfaces.begin_create_or_update(self.resource_group, self.name, nic)
868 new_nic = self.get_poller_result(poller)
869 return nic_to_dict(new_nic)
870 except Exception as exc:
871 self.fail("Error creating or updating network interface {0} - {1}".format(self.name, str(exc)))
872
873 def delete_nic(self):
874 try:
875 poller = self.network_client.network_interfaces.begin_delete(self.resource_group, self.name)
876 self.get_poller_result(poller)
877 except Exception as exc:
878 self.fail("Error deleting network interface {0} - {1}".format(self.name, str(exc)))
879 return True
880
881 def get_public_ip_address(self, name):
882 self.log("Fetching public ip address {0}".format(name))
883 try:
884 return self.network_client.public_ip_addresses.get(self.resource_group, name)
885 except ResourceNotFoundError as exc:
886 return None
887
888 def get_security_group(self, resource_group, name):
889 self.log("Fetching security group {0}".format(name))
890 try:
891 return self.network_client.network_security_groups.get(resource_group, name)
892 except ResourceNotFoundError as exc:
893 return None
894
895 def backend_addr_pool_id(self, val):
896 if isinstance(val, dict):
897 lb = val.get('load_balancer', None)
898 name = val.get('name', None)
899 if lb and name:
900 return resource_id(subscription=self.subscription_id,
901 resource_group=self.resource_group,
902 namespace='Microsoft.Network',
903 type='loadBalancers',
904 name=lb,
905 child_type_1='backendAddressPools',
906 child_name_1=name)
907 return val
908
909 def gateway_backend_addr_pool_id(self, val):
910 if isinstance(val, dict):
911 appgw = val.get('application_gateway', None)
912 name = val.get('name', None)
913 if appgw and name:
914 return resource_id(subscription=self.subscription_id,
915 resource_group=self.resource_group,
916 namespace='Microsoft.Network',
917 type='applicationGateways',
918 name=appgw,
919 child_type_1='backendAddressPools',
920 child_name_1=name)
921 return val
922
923 def construct_ip_configuration_set(self, raw):
924 configurations = [dict(
925 private_ip_allocation_method=to_native(item.get('private_ip_allocation_method')),
926 public_ip_address_name=(to_native(item.get('public_ip_address').get('name'))
927 if item.get('public_ip_address') else to_native(item.get('public_ip_address_name'))),
928 load_balancer_backend_address_pools=(sorted({to_native(self.backend_addr_pool_id(id))
929 for id in item.get('load_balancer_backend_address_pools', [])})
930 if item.get('load_balancer_backend_address_pools') else None),
931 application_gateway_backend_address_pools=(sorted({to_native(self.gateway_backend_addr_pool_id(id))
932 for id in item.get('application_gateway_backend_address_pools', [])})
933 if item.get('application_gateway_backend_address_pools') else None),
934 application_security_groups=(sorted({to_native(asg_id) for asg_id in item.get('application_security_groups', [])})
935 if item.get('application_security_groups') else None),
936 name=to_native(item.get('name')),
937 private_ip_address_version=to_native(item.get('private_ip_address_version')),
938 public_ip_allocation_method=to_native(item.get('public_ip_allocation_method', 'Dynamic')),
939 primary=bool(item.get('primary'))
940 ) for item in raw]
941 return sorted(configurations, key=lambda x: x['name'])
942
943
944 def main():
945 AzureRMNetworkInterface()
946
947
948 if __name__ == '__main__':
949 main()