Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_publicipaddress.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_publicipaddress
15
16 version_added: "0.1.0"
17
18 short_description: Manage Azure Public IP Addresses
19
20 description:
21 - Create, update and delete a Public IP address.
22 - Allows setting and updating the address allocation method and domain name label.
23 - Use the M(azure.azcollection.azure_rm_networkinterface) module to associate a Public IP with a network interface.
24
25 options:
26 resource_group:
27 description:
28 - Name of resource group with which the Public IP is associated.
29 required: true
30 type: str
31 allocation_method:
32 description:
33 - Control whether the assigned Public IP remains permanently assigned to the object.
34 - If not set to C(Static), the IP address may changed anytime an associated virtual machine is power cycled.
35 type: str
36 choices:
37 - dynamic
38 - static
39 - Static
40 - Dynamic
41 default: dynamic
42 domain_name:
43 description:
44 - The customizable portion of the FQDN assigned to public IP address. This is an explicit setting.
45 - If no value is provided, any existing value will be removed on an existing public IP.
46 type: str
47 aliases:
48 - domain_name_label
49 reverse_fqdn:
50 description:
51 - The reverse FQDN.
52 - A user-visible, fully qualified domain name that resolves to this public IP address.
53 - If the reverseFqdn is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN.
54 type: str
55 name:
56 description:
57 - Name of the Public IP.
58 type: str
59 required: true
60 public_ip_prefix:
61 description:
62 - The Public IP Prefix this Public IP Address should be allocated from.
63 - Once set, it cannot be updated.
64 type: dict
65 suboptions:
66 id:
67 description:
68 - The Public IP Prefix ID.
69 type: str
70 state:
71 description:
72 - Assert the state of the Public IP. Use C(present) to create or update a and C(absent) to delete.
73 default: present
74 type: str
75 choices:
76 - absent
77 - present
78 location:
79 description:
80 - Valid Azure location. Defaults to location of the resource group.
81 type: str
82 sku:
83 description:
84 - The public IP address SKU.
85 - When I(version=ipv6), if I(sku=standard) then set I(allocation_method=static).
86 - When I(version=ipv4), if I(sku=standard) then set I(allocation_method=static).
87 - The I(sku=basic) will be retired on September 30, 2025.
88 - New I(sku=basic) SKU resource cannot be deployed after March 31, 2025.
89 type: str
90 choices:
91 - standard
92 - Standard
93 ip_tags:
94 description:
95 - List of IpTag associated with the public IP address.
96 - Each element should contain type:value pair.
97 type: list
98 elements: dict
99 suboptions:
100 type:
101 description:
102 - Sets the ip_tags type.
103 type: str
104 required: true
105 value:
106 description:
107 - Sets the ip_tags value.
108 type: str
109 required: true
110 idle_timeout:
111 description:
112 - Idle timeout in minutes.
113 type: int
114 version:
115 description:
116 - The public IP address version.
117 type: str
118 choices:
119 - ipv4
120 - ipv6
121 default: ipv4
122 zones:
123 description:
124 - A list of availability zones denoting the IP allocated for the resource needs to come from.
125 type: list
126 elements: str
127 choices:
128 - '1'
129 - '2'
130 - '3'
131
132 extends_documentation_fragment:
133 - azure.azcollection.azure
134 - azure.azcollection.azure_tags
135
136 author:
137 - Chris Houseknecht (@chouseknecht)
138 - Matt Davis (@nitzmahone)
139 '''
140
141 EXAMPLES = '''
142 - name: Create a public ip address
143 azure_rm_publicipaddress:
144 resource_group: myResourceGroup
145 name: my_public_ip
146 allocation_method: static
147 domain_name: foobar
148
149 - name: Delete public ip
150 azure_rm_publicipaddress:
151 resource_group: myResourceGroup
152 name: my_public_ip
153 state: absent
154 '''
155
156 RETURN = '''
157 state:
158 description:
159 - Facts about the current state of the object.
160 returned: always
161 type: complex
162 contains:
163 id:
164 description:
165 - The resource's ID.
166 type: str
167 returned: always
168 sample: /subscriptions/xxx-xxx/resourceGroups/testRG/providers/Microsoft.Network/publicIPAddresses/pip01
169 dns_settings:
170 description:
171 - The FQDN of the DNS record associated with the public IP address.
172 returned: always
173 type: dict
174 sample: {
175 "domain_name_label": "ansible-b57dc95985712e45eb8b9c2e",
176 "fqdn": "ansible-b57dc95985712e45eb8b9c2e.eastus.cloudapp.azure.com",
177 "reverse_fqdn": "ansible-b57dc95985712e45eb8b9c2f.eastus.cloudapp.azure.com"
178 }
179 etag:
180 description:
181 - A unique read-only string that changes whenever the resource is updated.
182 returned: always
183 type: str
184 sample: "W/'1905ee13-7623-45b1-bc6b-4a12b2fb9d15'"
185 idle_timeout_in_minutes:
186 description:
187 - The idle timeout of the public IP address.
188 returned: always
189 type: int
190 sample: 4
191 ip_address:
192 description:
193 - The Public IP Prefix this Public IP Address should be allocated from.
194 returned: always
195 type: str
196 sample: 52.160.103.93
197 location:
198 description:
199 - Resource location.
200 returned: always
201 type: str
202 example: eastus
203 name:
204 description:
205 - Name of the Public IP Address.
206 returned: always
207 type: str
208 example: publicip002
209 provisioning_state:
210 description:
211 - The provisioning state of the Public IP resource.
212 returned: always
213 type: str
214 example: Succeeded
215 public_ip_allocation_method:
216 description:
217 - The public IP allocation method.
218 returned: always
219 type: str
220 sample: static
221 public_ip_address_version:
222 description:
223 - The public IP address version.
224 returned: always
225 type: str
226 sample: ipv4
227 public_ip_prefix:
228 description:
229 - The Public IP Prefix this Public IP Address should be allocated from.
230 type: dict
231 returned: when-used
232 sample: {"id": "/subscriptions/xxx-xxx/resourceGroups/testRG/providers/Microsoft.Network/publicIPPrefixes/prefix01"}
233 sku:
234 description:
235 - The public IP address SKU.
236 returned: always
237 type: str
238 sample: Standard
239 tags:
240 description:
241 - The resource tags.
242 returned: always
243 type: dict
244 sample: {
245 "delete": "on-exit",
246 "testing": "testing"
247 }
248 type:
249 description:
250 - Type of the resource.
251 returned: always
252 type: str
253 sample: "Microsoft.Network/publicIPAddresses"
254 zones:
255 description:
256 - A list of availability zones denoting the IP allocated for the resource needs to come from.
257 returned: always
258 type: list
259 sample: ['1', '2']
260 '''
261
262 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
263 from ansible.module_utils._text import to_native
264
265 try:
266 from azure.core.exceptions import ResourceNotFoundError
267 except ImportError:
268 # This is handled in azure_rm_common
269 pass
270
271
272 def pip_to_dict(pip):
273 result = dict(
274 name=pip.name,
275 id=pip.id,
276 type=pip.type,
277 location=pip.location,
278 tags=pip.tags,
279 public_ip_allocation_method=pip.public_ip_allocation_method.lower(),
280 public_ip_address_version=pip.public_ip_address_version.lower(),
281 dns_settings=dict(),
282 ip_address=pip.ip_address,
283 idle_timeout_in_minutes=pip.idle_timeout_in_minutes,
284 provisioning_state=pip.provisioning_state,
285 etag=pip.etag,
286 sku=pip.sku.name,
287 zones=pip.zones,
288 public_ip_prefix=None
289 )
290 if pip.dns_settings:
291 result['dns_settings']['domain_name_label'] = pip.dns_settings.domain_name_label
292 result['dns_settings']['fqdn'] = pip.dns_settings.fqdn
293 result['dns_settings']['reverse_fqdn'] = pip.dns_settings.reverse_fqdn
294 if pip.ip_tags:
295 result['ip_tags'] = [dict(type=to_native(x.ip_tag_type), value=to_native(x.tag)) for x in pip.ip_tags]
296 if pip.public_ip_prefix:
297 result['public_ip_prefix'] = dict(id=pip.public_ip_prefix.id)
298
299 return result
300
301
302 ip_tag_spec = dict(
303 type=dict(type='str', required=True),
304 value=dict(type='str', required=True)
305 )
306
307
308 class AzureRMPublicIPAddress(AzureRMModuleBase):
309
310 def __init__(self):
311
312 self.module_arg_spec = dict(
313 resource_group=dict(type='str', required=True),
314 name=dict(type='str', required=True),
315 state=dict(type='str', default='present', choices=['present', 'absent']),
316 location=dict(type='str'),
317 version=dict(type='str', default='ipv4', choices=['ipv4', 'ipv6']),
318 allocation_method=dict(type='str', default='dynamic', choices=['Dynamic', 'Static', 'dynamic', 'static']),
319 domain_name=dict(type='str', aliases=['domain_name_label']),
320 reverse_fqdn=dict(type='str'),
321 sku=dict(type='str', choices=['Standard', 'standard']),
322 ip_tags=dict(type='list', elements='dict', options=ip_tag_spec),
323 idle_timeout=dict(type='int'),
324 public_ip_prefix=dict(type='dict', options=dict(id=dict(type='str'))),
325 zones=dict(type='list', elements='str', choices=['1', '2', '3'])
326 )
327
328 self.resource_group = None
329 self.name = None
330 self.location = None
331 self.state = None
332 self.tags = None
333 self.zones = None
334 self.allocation_method = None
335 self.domain_name = None
336 self.reverse_fqdn = None
337 self.sku = None
338 self.version = None
339 self.ip_tags = None
340 self.idle_timeout = None
341 self.public_ip_prefix = None
342
343 self.results = dict(
344 changed=False,
345 state=dict()
346 )
347
348 super(AzureRMPublicIPAddress, self).__init__(derived_arg_spec=self.module_arg_spec,
349 supports_check_mode=True)
350
351 def exec_module(self, **kwargs):
352
353 for key in list(self.module_arg_spec.keys()) + ['tags']:
354 setattr(self, key, kwargs[key])
355
356 results = dict()
357 changed = False
358 pip = None
359
360 # capitalize the sku and allocation_method. standard => Standard, Standard => Standard.
361 self.allocation_method = self.allocation_method.capitalize() if self.allocation_method else None
362 self.sku = self.sku.capitalize() if self.sku else None
363 self.version = 'IPv4' if self.version == 'ipv4' else 'IPv6'
364
365 resource_group = self.get_resource_group(self.resource_group)
366 if not self.location:
367 # Set default location
368 self.location = resource_group.location
369
370 try:
371 self.log("Fetch public ip {0}".format(self.name))
372 pip = self.network_client.public_ip_addresses.get(self.resource_group, self.name)
373 self.check_provisioning_state(pip, self.state)
374 self.log("PIP {0} exists".format(self.name))
375 if self.state == 'present':
376 results = pip_to_dict(pip)
377 domain_lable = results['dns_settings'].get('domain_name_label')
378 if self.domain_name is not None and ((self.domain_name or domain_lable) and self.domain_name != domain_lable):
379 self.log('CHANGED: domain_name_label')
380 changed = True
381 results['dns_settings']['domain_name_label'] = self.domain_name
382
383 if self.reverse_fqdn is not None and self.reverse_fqdn != results['dns_settings'].get('reverse_fqdn'):
384 changed = True
385 self.log('CHANGED: reverse_fqdn')
386 else:
387 self.reverse_fqdn = results['dns_settings'].get('reverse_fqdn')
388
389 if self.allocation_method.lower() != results['public_ip_allocation_method'].lower():
390 self.log("CHANGED: allocation_method")
391 changed = True
392 results['public_ip_allocation_method'] = self.allocation_method
393
394 if self.sku and self.sku != results['sku']:
395 self.log("CHANGED: sku")
396 changed = True
397 results['sku'] = self.sku
398
399 if self.version.lower() != results['public_ip_address_version'].lower():
400 self.log("CHANGED: version")
401 changed = True
402 results['public_ip_address_version'] = self.version
403
404 if self.idle_timeout and self.idle_timeout != results['idle_timeout_in_minutes']:
405 self.log("CHANGED: idle_timeout")
406 changed = True
407 results['idle_timeout_in_minutes'] = self.idle_timeout
408
409 if self.zones and self.zones != results['zones']:
410 self.log("Zones defined do not same with existing zones")
411 changed = False
412 self.fail("ResourceAvailabilityZonesCannotBeModified: defines is {0}, existing is {1}".format(self.zones, results['zones']))
413
414 if str(self.ip_tags or []) != str(results.get('ip_tags') or []):
415 self.log("CHANGED: ip_tags")
416 changed = True
417 results['ip_tags'] = self.ip_tags
418
419 update_tags, results['tags'] = self.update_tags(results['tags'])
420 if update_tags:
421 changed = True
422
423 elif self.state == 'absent':
424 self.log("CHANGED: public ip {0} exists but requested state is 'absent'".format(self.name))
425 changed = True
426 except ResourceNotFoundError:
427 self.log('Public ip {0} does not exist'.format(self.name))
428 if self.state == 'present':
429 self.log("CHANGED: pip {0} does not exist but requested state is 'present'".format(self.name))
430 changed = True
431
432 self.results['state'] = results
433 self.results['changed'] = changed
434
435 if self.check_mode:
436 return dict(state=results)
437
438 if changed:
439 if self.state == 'present':
440 if not pip:
441 self.log("Create new Public IP {0}".format(self.name))
442 pip = self.network_models.PublicIPAddress(
443 location=self.location,
444 public_ip_address_version=self.version,
445 public_ip_prefix=self.public_ip_prefix,
446 public_ip_allocation_method=self.allocation_method,
447 sku=self.network_models.PublicIPAddressSku(name=self.sku) if self.sku else None,
448 idle_timeout_in_minutes=self.idle_timeout if self.idle_timeout and self.idle_timeout > 0 else None,
449 zones=self.zones
450 )
451 if self.ip_tags:
452 pip.ip_tags = [self.network_models.IpTag(ip_tag_type=x['type'], tag=x['value']) for x in self.ip_tags]
453 if self.tags:
454 pip.tags = self.tags
455 if self.domain_name or self.reverse_fqdn:
456 pip.dns_settings = self.network_models.PublicIPAddressDnsSettings(
457 domain_name_label=self.domain_name,
458 reverse_fqdn=self.reverse_fqdn
459 )
460 else:
461 self.log("Update Public IP {0}".format(self.name))
462 pip = self.network_models.PublicIPAddress(
463 location=results['location'],
464 public_ip_allocation_method=results['public_ip_allocation_method'],
465 sku=self.network_models.PublicIPAddressSku(name=self.sku) if self.sku else None,
466 tags=results['tags'],
467 public_ip_prefix=self.public_ip_prefix,
468 zones=results['zones']
469 )
470 if self.domain_name or self.reverse_fqdn:
471 pip.dns_settings = self.network_models.PublicIPAddressDnsSettings(
472 domain_name_label=self.domain_name,
473 reverse_fqdn=self.reverse_fqdn
474 )
475 self.results['state'] = self.create_or_update_pip(pip)
476 elif self.state == 'absent':
477 self.log('Delete public ip {0}'.format(self.name))
478 self.delete_pip()
479
480 return self.results
481
482 def create_or_update_pip(self, pip):
483 try:
484 poller = self.network_client.public_ip_addresses.begin_create_or_update(self.resource_group, self.name, pip)
485 pip = self.get_poller_result(poller)
486 except Exception as exc:
487 self.fail("Error creating or updating {0} - {1}".format(self.name, str(exc)))
488 return pip_to_dict(pip)
489
490 def delete_pip(self):
491 try:
492 poller = self.network_client.public_ip_addresses.begin_delete(self.resource_group, self.name)
493 self.get_poller_result(poller)
494 except Exception as exc:
495 self.fail("Error deleting {0} - {1}".format(self.name, str(exc)))
496 # Delete returns nada. If we get here, assume that all is well.
497 self.results['state']['status'] = 'Deleted'
498 return True
499
500
501 def main():
502 AzureRMPublicIPAddress()
503
504
505 if __name__ == '__main__':
506 main()