Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2022 xuzhang3 (@xuzhang3), Fred-sun (@Fred-sun)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 ---
14 module: azure_rm_privatelinkservice
15
16 version_added: "1.12.0"
17
18 short_description: Managed private link service resource
19
20 description:
21 - Create, Update or Delete private link service resource.
22
23 options:
24 name:
25 description:
26 - The name of the private link service.
27 type: str
28 required: True
29 resource_group:
30 description:
31 - The name of the resource group.
32 type: str
33 required: True
34 location:
35 description:
36 - The resource location.
37 type: str
38 load_balancer_frontend_ip_configurations:
39 description:
40 - An array of references to the load balancer IP configurations
41 - Cannot have more than one load balancer frontend IP configuration on the private link service.
42 type: list
43 elements: dict
44 suboptions:
45 id:
46 description:
47 - The load balancer frontend IP's ID.
48 type: str
49 fqdns:
50 description:
51 - The list of Fqdn.
52 elements: str
53 type: list
54 auto_approval:
55 description:
56 - The auto-approval list of the private link service.
57 type: dict
58 suboptions:
59 subscriptions:
60 description:
61 - The list of subscriptions.
62 type: list
63 elements: str
64 visibility:
65 description:
66 - The visibility list of the private link service.
67 type: dict
68 suboptions:
69 subscriptions:
70 description:
71 - The list of subscriptions.
72 type: list
73 elements: str
74 enable_proxy_protocol:
75 description:
76 - Whether the private link service is enabled for proxy protocol or not.
77 type: bool
78 ip_configurations:
79 description:
80 - An array of private link service IP configurations.
81 type: list
82 elements: dict
83 suboptions:
84 name:
85 description:
86 - The name of private link service ip configuration.
87 type: str
88 properties:
89 description:
90 - The property of the private link service IP configurations.
91 type: dict
92 suboptions:
93 primary:
94 description:
95 - Whether the ip configuration is primary or not.
96 type: bool
97 private_ip_allocation_method:
98 description:
99 - The private IP address allocation method.
100 type: str
101 choices:
102 - Static
103 - Dynamic
104 private_ip_address_version:
105 description:
106 - Whether the specific IP configuration is IPv4 or IPv6.
107 type: str
108 choices:
109 - IPv4
110 - IPv6
111 subnet:
112 description:
113 - The reference to the subnet resource.
114 type: dict
115 suboptions:
116 id:
117 description:
118 - The ID of the subnet.
119 type: str
120 state:
121 description:
122 - Assert the state of the pirvate link service.
123 - Use I(state=present) to create or update the link service and I(state=absent) to delete it.
124 type: str
125 default: present
126 choices:
127 - present
128 - absent
129
130 extends_documentation_fragment:
131 - azure.azcollection.azure
132 - azure.azcollection.azure_tags
133
134 author:
135 - xuzhang3 (@xuzhang3)
136 - Fred-sun (@Fred-sun)
137 '''
138
139 EXAMPLES = '''
140 - name: Create the private link service
141 azure_rm_privatelinkservice:
142 name: linkservice-name
143 resource_group: myResourceGroup
144 enable_proxy_protocol: true
145 fqdns:
146 - 'dns01.com'
147 - 'dns02.com'
148 visibility:
149 subscriptions:
150 - xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
151 - yyyyyy-yyyyy-yyyy-yyyy-yyyyyyyyyyy
152 auto_approval:
153 subscriptions:
154 - xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
155 - yyyyyy-yyyyy-yyyy-yyyy-yyyyyyyyyyy
156 load_balancer_frontend_ip_configurations:
157 - id: load_balancer_frontend_ip_configurations_id
158 ip_configurations:
159 - name: testSubnet
160 properties:
161 primary: false
162 private_ip_allocation_method: 'Dynamic'
163 private_ip_address_version: 'IPv4'
164 subnet:
165 id: subnet_id
166 - name: subnetfredprivate-1
167 properties:
168 primary: true
169 private_ip_allocation_method: 'Static'
170 private_ip_address_version: 'IPv4'
171 subnet:
172 id: subnet_id
173 tags:
174 key1: value1
175 key2: value2
176
177 - name: delete the private link service
178 azure_rm_privatelinkservice:
179 name: linkservice-name
180 resource_group: myResourceGroup
181 state: absent
182 '''
183
184 RETURN = '''
185 link_service:
186 description:
187 - List of private link service info.
188 returned: always
189 type: complex
190 contains:
191 id:
192 description:
193 - Resource ID of the private link service.
194 sample: "/subscriptions/xxx-xxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/privateLinkServices/linkservice"
195 returned: always
196 type: str
197 name:
198 description:
199 - Name of the private link service.
200 returned: always
201 type: str
202 sample: linkservice
203 location:
204 description:
205 - Resource location.
206 returned: always
207 type: str
208 sample: eastus
209 alias:
210 description:
211 - The alias of the private link service.
212 type: str
213 returned: always
214 sample: "linkservice.6a244dd8-8416-40cf-8c04-52b353bdd507.eastus.azure.privatelinkservice"
215 auto_approval:
216 description:
217 - The auto-approval list of the private link service.
218 type: dict
219 returned: always
220 sample: { "subscriptions": ['xxxx-xxxx', 'yyyy-yyyyy'] }
221 enable_proxy_protocol:
222 description:
223 - Whether the private link service is enabled for proxy protocol or not.
224 type: bool
225 returned: always
226 sample: False
227 etag:
228 description:
229 - A unique read-only string that changes whenever the resource is updated.
230 type: str
231 returned: always
232 sample: "f7d60f37-ea2b-4091-8546-1327f35468c4"
233 type:
234 description:
235 - The resource type.
236 type: str
237 returned: always
238 sample: Microsoft.Network/privateLinkServices
239 visibility:
240 description:
241 - The visibility list of the private link service.
242 type: dict
243 returned: always
244 sample: { "subscriptions": ['xxxx-xxxx', 'yyyy-yyyyy'] }
245 tags:
246 description:
247 - The resource tags.
248 type: dict
249 returned: always
250 sample: { 'key1': 'value1' }
251 provisioning_state:
252 description:
253 - The provisioning state of the private link service resource.
254 type: str
255 returned: always
256 sample: Succeeded
257 network_interfaces:
258 description:
259 - An array of references to the network interfaces created for this private link service.
260 type: list
261 returned: always
262 sample: [{ "id": "/subscriptions/xxx-xxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/testlinkservice.nic.f5"}]
263 ip_configurations:
264 description:
265 - An array of private link service IP configurations.
266 type: complex
267 returned: always
268 contains:
269 name:
270 description:
271 - The name of the IP configurations
272 type: str
273 returned: always
274 sample: subnetfredprivate-1
275 properties:
276 description:
277 - The IP configuration properties.
278 type: complex
279 returned: always
280 contains:
281 primary:
282 description:
283 - Whether the ip configuration is primary or not.
284 returned: always
285 type: bool
286 sample: True
287 private_ip_address_version:
288 description:
289 - Whether the specific IP configuration is IPv4 or IPv6.
290 returned: always
291 type: str
292 sample: IPv4
293 private_ip_allocation_method:
294 description:
295 - The private IP address allocation method.
296 returned: always
297 type: str
298 sample: Dynamic
299 subnet:
300 description:
301 - The reference to the subnet resource.
302 returned: always
303 type: dict
304 sample: { "id": "/subscriptions/xxx/resourceGroups/myRG/providers/Microsoft.Network/virtualNetworks/vnet/subnets/subnamee" }
305 load_balancer_frontend_ip_configurations:
306 description:
307 - An array of references to the load balancer IP configurations.
308 type: list
309 returned: awalys
310 sample: [{ "id": "/subscriptions/xxx/resourceGroups/myRG/providers/Microsoft.Network/loadBalancers/testlb/frontendIPConfigurations/front01" }]
311 fqdns:
312 description:
313 - The list of Fqdn.
314 type: list
315 returned: always
316 sample: ['fqdns1.com', 'fqdns2.com']
317 private_endpoint_connections:
318 description:
319 - An array of list about connections to the private endpoint.
320 type: complex
321 returned: always
322 contains:
323 id:
324 description:
325 - The ID of the private endpoint connection.
326 type: str
327 returned: always
328 sample: "/subscriptions/xxx/resourceGroups/myRG/providers/Microsoft.Network/privateLinkServices/linkservice/privateEndpointConnections/tes"
329 private_endpoint:
330 description:
331 - The ID of the private endpoint.
332 type: str
333 returned: always
334 sample: "/subscriptions/xxx-xxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/privateEndpoints/test002"
335 '''
336
337 try:
338 from azure.core.exceptions import ResourceNotFoundError
339 from azure.core.polling import LROPoller
340 except Exception:
341 # This is handled in azure_rm_common
342 pass
343
344
345 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
346
347 load_balancer_frontend_ip_configurations_spec = dict(
348 id=dict(type='str'),
349 )
350
351 auto_approval_spec = dict(
352 subscriptions=dict(type='list', elements='str')
353 )
354
355 visibility_spec = dict(
356 subscriptions=dict(type='list', elements='str')
357 )
358
359 properties_spec = dict(
360 primary=dict(type='bool'),
361 # private_ip_address=dict(type='str'),
362 private_ip_allocation_method=dict(type='str', choices=['Static', 'Dynamic']),
363 subnet=dict(type='dict', options=dict(id=dict(type='str'))),
364 private_ip_address_version=dict(type='str', choices=['IPv4', 'IPv6'])
365 )
366
367
368 class AzureRMPrivateLinkService(AzureRMModuleBase):
369
370 def __init__(self):
371
372 self.module_arg_spec = dict(
373 name=dict(type="str", required=True),
374 resource_group=dict(type="str", required=True),
375 state=dict(type='str', default='present', choices=['present', 'absent']),
376 location=dict(type='str'),
377 load_balancer_frontend_ip_configurations=dict(
378 type='list',
379 elements='dict',
380 options=load_balancer_frontend_ip_configurations_spec
381 ),
382 ip_configurations=dict(
383 type='list',
384 elements='dict',
385 options=dict(
386 name=dict(type='str'),
387 properties=dict(type='dict', options=properties_spec)
388 )
389 ),
390 visibility=dict(type='dict', options=visibility_spec),
391 fqdns=dict(type='list', elements='str'),
392 enable_proxy_protocol=dict(type='bool'),
393 auto_approval=dict(type='dict', options=auto_approval_spec),
394 )
395
396 self.name = None
397 self.resource_group = None
398 self.location = None
399 self.tags = None
400 self.state = None
401 self.results = dict(
402 changed=False,
403 )
404 self.body = {}
405
406 super(AzureRMPrivateLinkService, self).__init__(self.module_arg_spec,
407 supports_check_mode=True,
408 supports_tags=True,
409 facts_module=False)
410
411 def exec_module(self, **kwargs):
412 for key in list(self.module_arg_spec.keys()) + ['tags']:
413 if hasattr(self, key):
414 setattr(self, key, kwargs[key])
415 elif kwargs[key] is not None:
416 self.body[key] = kwargs[key]
417
418 old_response = self.get_item()
419 result = None
420 changed = False
421
422 if not self.location:
423 resource_group = self.get_resource_group(self.resource_group)
424 self.location = resource_group.location
425
426 self.body['location'] = self.location
427 self.body['tags'] = self.tags
428
429 if self.state == 'present':
430 if old_response:
431 update_tags, tags = self.update_tags(old_response['tags'])
432 if update_tags:
433 changed = True
434 self.body['tags'] = tags
435 if self.body.get('enable_proxy_protocol') is not None:
436 if self.body.get('enable_proxy_protocol') != old_response['enable_proxy_protocol']:
437 changed = True
438 else:
439 self.body['enable_proxy_protocol'] = old_response['enable_proxy_protocol']
440
441 if self.body.get("auto_approval") is not None:
442 for value in old_response["auto_approval"]['subscriptions']:
443 if value not in self.body["auto_approval"]['subscriptions']:
444 self.body["auto_approval"]['subscriptions'].append(value)
445 if len(self.body["auto_approval"]['subscriptions']) != len(old_response["auto_approval"]['subscriptions']):
446 changed = True
447 else:
448 self.body["auto_approval"] = old_response["auto_approval"]
449
450 if self.body.get("visibility") is not None:
451 for value in old_response["visibility"]['subscriptions']:
452 if value not in self.body["visibility"]['subscriptions']:
453 self.body["visibility"]['subscriptions'].append(value)
454 if len(self.body["visibility"]['subscriptions']) != len(old_response["visibility"]['subscriptions']):
455 changed = True
456 else:
457 self.body["visibility"] = old_response["visibility"]
458
459 if self.body.get('fqdns') is not None:
460 for value in old_response['fqdns']:
461 if value not in self.body['fqdns']:
462 self.body['fqdns'].append(value)
463 if len(self.body.get('fqdns')) != len(old_response['fqdns']):
464 changed = True
465 else:
466 self.body['fqdns'] = old_response['fqdns']
467
468 if self.body.get('load_balancer_frontend_ip_configurations') is not None:
469 if self.body['load_balancer_frontend_ip_configurations'] != old_response['load_balancer_frontend_ip_configurations']:
470 self.fail("Private Link Service Load Balancer Reference Cannot Be Changed")
471 else:
472 self.body['load_balancer_frontend_ip_configurations'] = old_response['load_balancer_frontend_ip_configurations']
473
474 if self.body.get('ip_configurations') is not None:
475 for items in old_response['ip_configurations']:
476 if items['name'] not in [item['name'] for item in self.body['ip_configurations']]:
477 self.body['ip_configurations'].append(items)
478 if len(self.body['ip_configurations']) != len(old_response['ip_configurations']):
479 changed = True
480 else:
481 self.body['ip_configurations'] = old_response['ip_configurations']
482 else:
483 changed = True
484
485 if changed:
486 if self.check_mode:
487 self.log("Check mode test. The private link service is exist, will be create or updated")
488 else:
489 result = self.create_or_update(self.body)
490 else:
491 if self.check_mode:
492 self.log("Check mode test. The private endpoint connection is exist, No operation in this task")
493 else:
494 self.log("The private endpoint connection is exist, No operation in this task")
495 result = old_response
496 else:
497 if old_response:
498 changed = True
499 if self.check_mode:
500 self.log("Check mode test. The private link service is exist, will be deleted")
501 else:
502 result = self.delete_resource()
503 else:
504 if self.check_mode:
505 self.log("The private link service isn't exist, no action")
506 else:
507 self.log("The private link service isn't exist, don't need to delete")
508
509 self.results["link_service"] = result
510 self.results['changed'] = changed
511 return self.results
512
513 def get_item(self):
514 self.log("Get properties for {0} in {1}".format(self.name, self.resource_group))
515 try:
516 response = self.network_client.private_link_services.get(self.resource_group, self.name)
517 return self.service_to_dict(response)
518 except ResourceNotFoundError:
519 self.log("Could not get info for {0} in {1}".format(self.name, self.resource_group))
520
521 return []
522
523 def create_or_update(self, parameters):
524 self.log("Create or update the private link service for {0} in {1}".format(self.name, self.resource_group))
525 try:
526 response = self.network_client.private_link_services.begin_create_or_update(self.resource_group, self.name, parameters)
527 if isinstance(response, LROPoller):
528 response = self.get_poller_result(response)
529
530 result = self.network_client.private_link_services.get(self.resource_group, self.name)
531 return self.service_to_dict(result)
532 except Exception as ec:
533 self.fail("Create or Update {0} in {1} failed, mesage {2}".format(self.name, self.resource_group, ec))
534
535 return []
536
537 def delete_resource(self):
538 self.log("delete the private link service for {0} in {1}".format(self.name, self.resource_group))
539 try:
540 response = self.network_client.private_link_services.begin_delete(self.resource_group, self.name)
541 if isinstance(response, LROPoller):
542 response = self.get_poller_result(response)
543 return response
544 except Exception as ec:
545 self.fail("Delete {0} in {1} failed, message {2}".format(self.name, self.resource_group, ec))
546
547 return []
548
549 def service_to_dict(self, service_info):
550
551 service = service_info.as_dict()
552 result = dict(
553 id=service.get("id"),
554 name=service.get('name'),
555 type=service.get('type'),
556 etag=service.get('etag'),
557 location=service.get('location'),
558 tags=service.get('tags'),
559 load_balancer_frontend_ip_configurations=service.get('load_balancer_frontend_ip_configurations'),
560 ip_configurations=list(),
561 network_interfaces=service.get('network_interfaces'),
562 provisioning_state=service.get('provisioning_state'),
563 private_endpoint_connections=list(),
564 visibility=service.get('visibility'),
565 fqdns=service.get('fqdns'),
566 auto_approval=service.get('auto_approval'),
567 alias=service.get('alias'),
568 enable_proxy_protocol=service.get('enable_proxy_protocol')
569 )
570 if service.get('private_endpoint_connections'):
571 for items in service['private_endpoint_connections']:
572 result['private_endpoint_connections'].append({'id': items['id'], 'private_endpoint': items['private_endpoint']['id']})
573
574 if service.get('ip_configurations'):
575 for items in service['ip_configurations']:
576 result['ip_configurations'].append(
577 {
578 "name": items['name'],
579 'properties': {
580 "primary": items['primary'],
581 "private_ip_address_version": items["private_ip_address_version"],
582 "private_ip_allocation_method": items["private_ip_allocation_method"],
583 "subnet": items["subnet"],
584 }
585 }
586 )
587
588 return result
589
590
591 def main():
592 AzureRMPrivateLinkService()
593
594
595 if __name__ == "__main__":
596 main()