Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2024 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 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_publicipprefix
14
15 version_added: "2.2.0"
16
17 short_description: Manage Azure Public IP prefix
18
19 description:
20 - Create, update and delete a Public IP prefix.
21
22 options:
23 resource_group:
24 description:
25 - Name of resource group with which the Public IP prefix is associated.
26 required: true
27 type: str
28 name:
29 description:
30 - Name of the Public IP prefix.
31 required: true
32 type: str
33 state:
34 description:
35 - Assert the state of the Public IP. Use C(present) to create or update a and C(absent) to delete.
36 default: present
37 type: str
38 choices:
39 - absent
40 - present
41 location:
42 description:
43 - Valid Azure location. Defaults to location of the resource group.
44 type: str
45 sku:
46 description:
47 - The public IP prefix SKU.
48 type: dict
49 suboptions:
50 name:
51 description:
52 - Name of a public IP prefix SKU.
53 type: str
54 choices:
55 - Standard
56 tier:
57 description:
58 - Tier of a public IP prefix SKU.
59 type: str
60 choices:
61 - Regional
62 - Global
63 custom_ip_prefix:
64 description:
65 - The Custom IP prefix that this prefix is associated with.
66 type: dict
67 suboptions:
68 id:
69 description:
70 - Resource ID.
71 type: str
72 extended_location:
73 description:
74 - The extended location of the public ip address.
75 type: str
76 ip_tags:
77 description:
78 - The list of tags associated with the public IP prefix.
79 type: list
80 elements: dict
81 suboptions:
82 ip_tag_type:
83 description:
84 - The IP tag type. Example as FirstPartyUsage.
85 type: str
86 tag:
87 description:
88 - The value of the IP tag associated with the public IP. Example as SQL.
89 type: str
90 public_ip_address_version:
91 description:
92 - The public IP address version.
93 type: str
94 choices:
95 - IPV4
96 - IPV6
97 zones:
98 description:
99 - A list of availability zones denoting the IP prefix allocated for the resource needs to come from.
100 type: list
101 elements: str
102 choices:
103 - '1'
104 - '2'
105 - '3'
106 prefix_length:
107 description:
108 - The Length of the Public IP Prefix.
109 type: int
110
111 extends_documentation_fragment:
112 - azure.azcollection.azure
113 - azure.azcollection.azure_tags
114
115 author:
116 - xuzhang3 (@xuzhang3)
117 - Fred-sun (@Fred-sun)
118 '''
119
120 EXAMPLES = '''
121 - name: Create a public ip prefix
122 azure_rm_publicipprefix:
123 resource_group: myResourceGroup
124 name: my_public_ip
125 public_ip_address_version: IPV4
126 prefix_length: 29
127 sku:
128 name: Standard
129 tier: Regional
130 zones:
131 - 1
132 tags:
133 key1: value1
134
135 - name: Delete public ip prefix
136 azure_rm_publicipprefix:
137 resource_group: myResourceGroup
138 name: my_public_ipprefix
139 state: absent
140 '''
141
142 RETURN = '''
143 state:
144 description:
145 - List of public IP prefixes dicts.
146 returned: always
147 type: complex
148 contains:
149 id:
150 description:
151 - Resource ID.
152 returned: always
153 type: str
154 sample: /subscriptions/xxx---xxxxx/resourceGroups/v-xisuRG/providers/Microsoft.Network/publicIPPrefixes/pipb57dc95224
155 name:
156 description:
157 - Name of the public IP prefix.
158 returned: always
159 type: str
160 sample: prefix57dc95224
161 type:
162 description:
163 - Resource type.
164 returned: always
165 type: str
166 sample: "Microsoft.Network/publicIPPrefixes"
167 location:
168 description:
169 - Resource location.
170 returned: always
171 type: str
172 sample: eastus
173 tags:
174 description:
175 - Resource tags.
176 returned: always
177 type: dict
178 sample: {
179 "delete": "on-exit",
180 "testing": "testing"
181 }
182 public_ip_address_version:
183 description:
184 - The public IP address version.
185 - Possible values are C(IPv4) and C(IPv6).
186 returned: always
187 type: str
188 sample: IPv4
189 ip_tags:
190 description:
191 - The list of tags associated with the public IP prefixes.
192 returned: always
193 type: list
194 sample: [{'type': 'FirstPartyUsage', 'value': 'Storage'}]
195 resource_guid:
196 description:
197 - The resource GUID property of the public IP prefix resource.
198 type: str
199 sample: "47cafa04-851d-4579-894d-74ad6afe3233"
200 custom_ip_prefix:
201 description:
202 - The customIpPrefix that this prefix is associated with.
203 type: dict
204 returned: always
205 sample: {}
206 public_ip_addresses:
207 description:
208 - The list of all referenced PublicIPAddresses.
209 type: list
210 sample: []
211 '''
212
213 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
214
215 try:
216 from azure.core.exceptions import ResourceNotFoundError
217 except ImportError:
218 # This is handled in azure_rm_common
219 pass
220
221
222 def prefix_to_dict(prefix):
223 result = dict(
224 id=prefix.id,
225 name=prefix.name,
226 tags=prefix.tags,
227 type=prefix.type,
228 location=prefix.location,
229 public_ip_address_version=prefix.public_ip_address_version,
230 prefix_length=prefix.prefix_length,
231 provisioning_state=prefix.provisioning_state,
232 etag=prefix.etag,
233 zones=prefix.zones,
234 sku=dict(),
235 ip_tags=list(),
236 custom_ip_prefix=dict(),
237 ip_prefix=prefix.ip_prefix,
238 resource_guid=prefix.resource_guid,
239 public_ip_addresses=list(),
240 extended_location=prefix.extended_location
241 )
242 if prefix.public_ip_addresses:
243 result['public_ip_addresses'] = [x.id for x in prefix.public_ip_addresses]
244 if prefix.sku:
245 result['sku']['name'] = prefix.sku.name
246 result['sku']['tier'] = prefix.sku.tier
247 if prefix.custom_ip_prefix:
248 result['custom_ip_prefix']['id'] = prefix.custom_ip_prefix.id
249 if prefix.ip_tags:
250 result['ip_tags'] = [dict(type=x.ip_tag_type, value=x.tag) for x in prefix.ip_tags]
251 return result
252
253
254 class AzureRMPublicIPPrefix(AzureRMModuleBase):
255
256 def __init__(self):
257
258 self.module_arg_spec = dict(
259 resource_group=dict(type='str', required=True),
260 name=dict(type='str', required=True),
261 state=dict(type='str', default='present', choices=['present', 'absent']),
262 location=dict(type='str'),
263 public_ip_address_version=dict(type='str', choices=['IPV4', 'IPV6']),
264 extended_location=dict(type='str'),
265 prefix_length=dict(type='int'),
266 custom_ip_prefix=dict(
267 type='dict',
268 options=dict(
269 id=dict(type='str')
270 )
271 ),
272 sku=dict(
273 type='dict',
274 options=dict(
275 name=dict(type='str', choices=['Standard']),
276 tier=dict(type='str', choices=['Regional', 'Global'])
277 )
278 ),
279 ip_tags=dict(
280 type='list',
281 elements='dict',
282 options=dict(
283 ip_tag_type=dict(type='str'),
284 tag=dict(type='str')
285 )
286 ),
287 zones=dict(type='list', elements='str', choices=['1', '2', '3'])
288 )
289
290 self.resource_group = None
291 self.name = None
292 self.location = None
293 self.state = None
294 self.tags = None
295 self.zones = None
296 self.sku = None
297 self.ip_tags = None
298 self.public_ip_address_version = None
299 self.prefix_length = None
300 self.custom_ip_prefix = None
301
302 self.results = dict(
303 changed=False,
304 state=dict()
305 )
306
307 super(AzureRMPublicIPPrefix, self).__init__(derived_arg_spec=self.module_arg_spec,
308 supports_check_mode=True)
309
310 def exec_module(self, **kwargs):
311
312 for key in list(self.module_arg_spec.keys()) + ['tags']:
313 setattr(self, key, kwargs[key])
314
315 results = dict()
316 changed = False
317 prefix = None
318 update_tags = False
319
320 resource_group = self.get_resource_group(self.resource_group)
321 if not self.location:
322 # Set default location
323 self.location = resource_group.location
324
325 try:
326 self.log("Fetch public ip prefix {0}".format(self.name))
327 prefix = self.network_client.public_ip_prefixes.get(self.resource_group, self.name)
328 self.log("Public IP prefix {0} exists".format(self.name))
329
330 if self.state == 'present':
331 results = prefix_to_dict(prefix)
332
333 if self.public_ip_address_version is not None and \
334 self.public_ip_address_version.lower() != results['public_ip_address_version'].lower():
335 changed = False
336 results['public_ip_address_version'] = self.public_ip_address_version
337 self.fail("The public_ip_address_version can't be updated")
338
339 if self.prefix_length is not None and self.prefix_length != results['prefix_length']:
340 changed = False
341 results['prefix_length'] = self.prefix_length
342 self.fail("The prefix_length can't be updated")
343
344 if self.sku is not None:
345 for key in self.sku.keys():
346 if self.sku[key] != results['sku'].get(key):
347 changed = False
348 self.fail("The sku can't be updated")
349 results['sku'] = self.sku
350
351 if self.zones is not None and not all(key in results['zones'] for key in self.zones):
352 changed = False
353 results['zones'] = self.zones
354 self.fail("The zone can't be updated")
355
356 if self.extended_location is not None and self.extended_location != results['extended_location']:
357 changed = False
358 results['extended_location'] = self.extended_location
359 self.fail("The extended_location can't be updated")
360
361 if self.ip_tags is not None:
362 for key in self.ip_tags.keys():
363 if self.ip_tags[key] != results['ip_tags'].get(key):
364 changed = False
365 results['ip_tags'] = self.ip_tags
366 self.fail("The ip_tags can't be updated")
367
368 if self.custom_ip_prefix is not None:
369 if results.get('custom_ip_prefix') is None:
370 changed = False
371 results['custom_ip_prefix'] = self.custom_ip_prefix
372 self.fail("The custom_ip_prefix can't be updated")
373 elif self.custom_ip_prefix['id'].lower() != results['custom_ip_prefix']['id'].lower():
374 changed = False
375 results['custom_ip_prefix'] = self.custom_ip_prefix
376 self.fail("The custom_ip_prefix can't be updated")
377
378 update_tags, results['tags'] = self.update_tags(results['tags'])
379 if update_tags:
380 self.log("CHANGED: tags")
381 changed = True
382 self.tags = results['tags']
383
384 elif self.state == 'absent':
385 self.log("CHANGED: public ip prefix {0} exists but requested state is 'absent'".format(self.name))
386 changed = True
387 except ResourceNotFoundError:
388 self.log('Public ip prefix {0} does not exist'.format(self.name))
389 if self.state == 'present':
390 self.log("CHANGED: public IP prefix {0} does not exist but requested state is 'present'".format(self.name))
391 changed = True
392
393 self.results['state'] = results
394 self.results['changed'] = changed
395
396 if self.check_mode:
397 results['changed'] = True
398 return results
399
400 if update_tags:
401 self.results['state'] = self.update_prefix_tags(self.tags)
402
403 elif changed:
404 if self.state == 'present':
405 self.log("Create or Update Public IP prefix {0}".format(self.name))
406 prefix = self.network_models.PublicIPPrefix(
407 location=self.location,
408 public_ip_address_version=self.public_ip_address_version,
409 prefix_length=self.prefix_length,
410 zones=self.zones,
411 tags=self.tags,
412 sku=self.sku,
413 ip_tags=self.ip_tags,
414 custom_ip_prefix=self.custom_ip_prefix
415 )
416 self.results['state'] = self.create_or_update_prefix(prefix)
417
418 elif self.state == 'absent':
419 self.log('Delete public ip {0}'.format(self.name))
420 self.delete_prefix()
421
422 return self.results
423
424 def update_prefix_tags(self, tags):
425 try:
426 prefix = self.network_client.public_ip_prefixes.update_tags(self.resource_group, self.name, dict(tags=tags))
427 except Exception as exc:
428 self.fail("Error updating tags {0} - {1}".format(self.name, str(exc)))
429 return prefix_to_dict(prefix)
430
431 def create_or_update_prefix(self, prefix):
432 try:
433 poller = self.network_client.public_ip_prefixes.begin_create_or_update(self.resource_group, self.name, prefix)
434 prefix = self.get_poller_result(poller)
435 except Exception as exc:
436 self.fail("Error creating or updating {0} - {1}".format(self.name, str(exc)))
437 return prefix_to_dict(prefix)
438
439 def delete_prefix(self):
440 try:
441 poller = self.network_client.public_ip_prefixes.begin_delete(self.resource_group, self.name)
442 self.get_poller_result(poller)
443 except Exception as exc:
444 self.fail("Error deleting {0} - {1}".format(self.name, str(exc)))
445
446 self.results['state']['status'] = 'Deleted'
447 return True
448
449
450 def main():
451 AzureRMPublicIPPrefix()
452
453
454 if __name__ == '__main__':
455 main()