Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_eip.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: ec2_eip
10 version_added: 5.0.0
11 short_description: manages EC2 elastic IP (EIP) addresses.
12 description:
13 - This module can allocate or release an EIP.
14 - This module can associate/disassociate an EIP with instances or network interfaces.
15 - This module was originally added to C(community.aws) in release 1.0.0.
16 options:
17 device_id:
18 description:
19 - The id of the device for the EIP.
20 - Can be an EC2 Instance id or Elastic Network Interface (ENI) id.
21 - When specifying an ENI id, O(in_vpc) must be V(true).
22 - The C(instance_id) alias was removed in release 6.0.0.
23 required: false
24 type: str
25 public_ip:
26 description:
27 - The IP address of a previously allocated EIP.
28 - When O(state=present) and device is specified, the EIP is associated with the device.
29 - When O(state=absent) and device is specified, the EIP is disassociated from the device.
30 aliases: [ ip ]
31 type: str
32 state:
33 description:
34 - When O(state=present), allocate an EIP or associate an existing EIP with a device.
35 - When O(state=absent), disassociate the EIP from the device and optionally release it.
36 choices: ['present', 'absent']
37 default: present
38 type: str
39 in_vpc:
40 description:
41 - Allocate an EIP inside a VPC or not.
42 - Required if specifying an ENI with O(device_id).
43 default: false
44 type: bool
45 reuse_existing_ip_allowed:
46 description:
47 - Reuse an EIP that is not associated to a device (when available), instead of allocating a new one.
48 default: false
49 type: bool
50 release_on_disassociation:
51 description:
52 - Whether or not to automatically release the EIP when it is disassociated.
53 default: false
54 type: bool
55 private_ip_address:
56 description:
57 - The primary or secondary private IP address to associate with the Elastic IP address.
58 type: str
59 allow_reassociation:
60 description:
61 - Specify this option to allow an Elastic IP address that is already associated with another
62 network interface or instance to be re-associated with the specified instance or interface.
63 default: false
64 type: bool
65 tag_name:
66 description:
67 - When O(reuse_existing_ip_allowed=true), supplement with this option to only reuse
68 an Elastic IP if it is tagged with O(tag_name).
69 type: str
70 tag_value:
71 description:
72 - Supplements O(tag_name) but also checks that the value of the tag provided in O(tag_name) matches O(tag_value).
73 type: str
74 public_ipv4_pool:
75 description:
76 - Allocates the new Elastic IP from the provided public IPv4 pool (BYOIP)
77 only applies to newly allocated Elastic IPs, isn't validated when O(reuse_existing_ip_allowed=true).
78 type: str
79 domain_name:
80 description: The domain name to attach to the IP address.
81 required: false
82 type: str
83 version_added: 9.0.0
84 extends_documentation_fragment:
85 - amazon.aws.common.modules
86 - amazon.aws.region.modules
87 - amazon.aws.tags
88 - amazon.aws.boto3
89
90 author:
91 - "Rick Mendes (@rickmendes) <[email protected]>"
92 notes:
93 - There may be a delay between the time the EIP is assigned and when
94 the cloud instance is reachable via the new address. Use wait_for and
95 pause to delay further playbook execution until the instance is reachable,
96 if necessary.
97 - This module returns multiple changed statuses on disassociation or release.
98 It returns an overall status based on any changes occurring. It also returns
99 individual changed statuses for disassociation and release.
100 - Support for O(tags) and O(purge_tags) was added in release 2.1.0.
101 """
102
103 EXAMPLES = r"""
104 # Note: These examples do not set authentication details, see the AWS Guide for details.
105
106 - name: associate an elastic IP with an instance
107 amazon.aws.ec2_eip:
108 device_id: i-1212f003
109 ip: 93.184.216.119
110
111 - name: associate an elastic IP with a device
112 amazon.aws.ec2_eip:
113 device_id: eni-c8ad70f3
114 ip: 93.184.216.119
115
116 - name: associate an elastic IP with a device and allow reassociation
117 amazon.aws.ec2_eip:
118 device_id: eni-c8ad70f3
119 public_ip: 93.184.216.119
120 allow_reassociation: true
121
122 - name: disassociate an elastic IP from an instance
123 amazon.aws.ec2_eip:
124 device_id: i-1212f003
125 ip: 93.184.216.119
126 state: absent
127
128 - name: disassociate an elastic IP with a device
129 amazon.aws.ec2_eip:
130 device_id: eni-c8ad70f3
131 ip: 93.184.216.119
132 state: absent
133
134 - name: allocate a new elastic IP and associate it with an instance
135 amazon.aws.ec2_eip:
136 device_id: i-1212f003
137
138 - name: allocate a new elastic IP without associating it to anything
139 amazon.aws.ec2_eip:
140 state: present
141 register: eip
142
143 - name: output the IP
144 ansible.builtin.debug:
145 msg: "Allocated IP is {{ eip.public_ip }}"
146
147 - name: provision new instances with ec2
148 amazon.aws.ec2:
149 keypair: mykey
150 instance_type: c1.medium
151 image: ami-40603AD1
152 wait: true
153 group: webserver
154 count: 3
155 register: ec2
156
157 - name: associate new elastic IPs with each of the instances
158 amazon.aws.ec2_eip:
159 device_id: "{{ item }}"
160 loop: "{{ ec2.instance_ids }}"
161
162 - name: allocate a new elastic IP inside a VPC in us-west-2
163 amazon.aws.ec2_eip:
164 region: us-west-2
165 in_vpc: true
166 register: eip
167
168 - name: output the IP
169 ansible.builtin.debug:
170 msg: "Allocated IP inside a VPC is {{ eip.public_ip }}"
171
172 - name: allocate eip - reuse unallocated ips (if found) with FREE tag
173 amazon.aws.ec2_eip:
174 region: us-east-1
175 in_vpc: true
176 reuse_existing_ip_allowed: true
177 tag_name: FREE
178
179 - name: allocate eip - reuse unallocated ips if tag reserved is nope
180 amazon.aws.ec2_eip:
181 region: us-east-1
182 in_vpc: true
183 reuse_existing_ip_allowed: true
184 tag_name: reserved
185 tag_value: nope
186
187 - name: allocate new eip - from servers given ipv4 pool
188 amazon.aws.ec2_eip:
189 region: us-east-1
190 in_vpc: true
191 public_ipv4_pool: ipv4pool-ec2-0588c9b75a25d1a02
192
193 - name: allocate eip - from a given pool (if no free addresses where dev-servers tag is dynamic)
194 amazon.aws.ec2_eip:
195 region: us-east-1
196 in_vpc: true
197 reuse_existing_ip_allowed: true
198 tag_name: dev-servers
199 public_ipv4_pool: ipv4pool-ec2-0588c9b75a25d1a02
200
201 - name: allocate eip from pool - check if tag reserved_for exists and value is our hostname
202 amazon.aws.ec2_eip:
203 region: us-east-1
204 in_vpc: true
205 reuse_existing_ip_allowed: true
206 tag_name: reserved_for
207 tag_value: "{{ inventory_hostname }}"
208 public_ipv4_pool: ipv4pool-ec2-0588c9b75a25d1a02
209
210 - name: create new IP and modify it's reverse DNS record
211 amazon.aws.ec2_eip:
212 state: present
213 domain_name: test-domain.xyz
214
215 - name: Modify reverse DNS record of an existing EIP
216 amazon.aws.ec2_eip:
217 public_ip: 44.224.84.105
218 domain_name: test-domain.xyz
219 state: present
220
221 - name: Remove reverse DNS record of an existing EIP
222 amazon.aws.ec2_eip:
223 public_ip: 44.224.84.105
224 domain_name: ""
225 state: present
226 """
227
228 RETURN = r"""
229 allocation_id:
230 description: Allocation id of the elastic ip.
231 returned: on success
232 type: str
233 sample: eipalloc-51aa3a6c
234 public_ip:
235 description: An elastic ip address.
236 returned: on success
237 type: str
238 sample: 52.88.159.209
239 update_reverse_dns_record_result:
240 description: Information about result of update reverse dns record operation.
241 returned: When O(domain_name) is specified.
242 type: dict
243 contains:
244 address:
245 description: Information about the Elastic IP address.
246 returned: always
247 type: dict
248 contains:
249 allocation_id:
250 description: The allocation ID.
251 returned: always
252 type: str
253 sample: "eipalloc-00a11aa111aaa1a11"
254 ptr_record:
255 description: The pointer (PTR) record for the IP address.
256 returned: always
257 type: str
258 sample: "ec2-11-22-33-44.us-east-2.compute.amazonaws.com."
259 ptr_record_update:
260 description: The updated PTR record for the IP address.
261 returned: always
262 type: dict
263 contains:
264 status:
265 description: The status of the PTR record update.
266 returned: always
267 type: str
268 sample: "PENDING"
269 value:
270 description: The value for the PTR record update.
271 returned: always
272 type: str
273 sample: "example.com"
274 public_ip:
275 description: The public IP address.
276 returned: always
277 type: str
278 sample: "11.22.33.44"
279 """
280
281 from typing import Any
282 from typing import Dict
283 from typing import List
284 from typing import Optional
285 from typing import Tuple
286 from typing import Union
287
288 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
289
290 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
291 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import allocate_address as allocate_ip_address
292 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import associate_address
293 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_addresses
294 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_instances
295 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_network_interfaces
296 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import disassociate_address
297 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
298 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import release_address
299 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
300 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
301 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
302
303
304 def find_address(
305 ec2, public_ip: Optional[str], device_id: Optional[str], is_instance
306 ) -> Optional[Dict[str, Union[str, List[Dict[str, str]]]]]:
307 """Find an existing Elastic IP address"""
308 filters = None
309
310 if not public_ip and not device_id:
311 return None
312
313 if public_ip:
314 params = {"PublicIps": [public_ip]}
315 else:
316 if is_instance:
317 filters = [{"Name": "instance-id", "Values": [device_id]}]
318 else:
319 filters = [{"Name": "network-interface-id", "Values": [device_id]}]
320 params = {"Filters": filters}
321
322 result = None
323 addresses = describe_addresses(ec2, **params)
324 if addresses:
325 if len(addresses) > 1:
326 raise AnsibleEC2Error(f"Found more than one address using args {params} Addresses found: {addresses}")
327 result = addresses[0]
328 return result
329
330
331 def address_is_associated_with_device(
332 ec2,
333 address: Optional[Dict[str, str]],
334 device_id: str,
335 is_instance: bool = True,
336 ) -> Optional[str]:
337 """Check if the elastic IP is currently associated with the device and return the association Id"""
338 public_ip = None if not address else address.get("PublicIp")
339 result = find_address(ec2, public_ip, device_id, is_instance)
340 association_id = None
341 if result:
342 instance_id = result.get("InstanceId") if is_instance else result.get("NetworkInterfaceId")
343 if instance_id == device_id:
344 association_id = result.get("AssociationId")
345 return association_id
346
347
348 def allocate_address(
349 client,
350 check_mode: bool,
351 search_tags: Optional[Dict[str, str]],
352 domain: Optional[str],
353 reuse_existing_ip_allowed: bool,
354 tags: Optional[Dict[str, str]],
355 public_ipv4_pool: Optional[bool] = None,
356 ) -> Tuple[Dict[str, str], bool]:
357 """Allocate a new elastic IP address (when needed) and return it"""
358 if not domain:
359 domain = "standard"
360
361 if reuse_existing_ip_allowed:
362 filters = []
363 filters.append({"Name": "domain", "Values": [domain]})
364
365 if search_tags is not None:
366 filters += ansible_dict_to_boto3_filter_list(search_tags)
367
368 all_addresses = describe_addresses(client, Filters=filters)
369
370 if domain == "vpc":
371 unassociated_addresses = [a for a in all_addresses if not a.get("AssociationId", None)]
372 else:
373 unassociated_addresses = [a for a in all_addresses if not a["InstanceId"]]
374 if unassociated_addresses:
375 return unassociated_addresses[0], False
376
377 params = {"Domain": domain}
378 if public_ipv4_pool:
379 params.update({"PublicIpv4Pool": public_ipv4_pool})
380 if tags:
381 params["TagSpecifications"] = boto3_tag_specifications(tags, types="elastic-ip")
382 address = None
383 if not check_mode:
384 address = allocate_ip_address(client, **params)
385 return address, True
386
387
388 def find_device(client, device_id: str, is_instance: bool) -> Optional[Dict[str, Any]]:
389 """Attempt to find the EC2 instance and return it"""
390
391 result = None
392 if is_instance:
393 reservations = describe_instances(client, InstanceIds=[device_id])
394 if len(reservations) == 1:
395 instances = reservations[0]["Instances"]
396 if len(instances) == 1:
397 result = instances[0]
398 else:
399 interfaces = describe_network_interfaces(client, NetworkInterfaceIds=[device_id])
400 if len(interfaces) == 1:
401 result = interfaces[0]
402 return result
403
404
405 def generate_tag_dict(module: AnsibleAWSModule) -> Optional[Dict[str, str]]:
406 """Generates a dictionary to be passed as a filter to Amazon"""
407 tag_name = module.params.get("tag_name")
408 tag_value = module.params.get("tag_value")
409 result = None
410
411 if not tag_name:
412 return result
413
414 if not tag_value:
415 if tag_name.startswith("tag:"):
416 tag_name = tag_name.strip("tag:")
417 result = {"tag-key": tag_name}
418 else:
419 if not tag_name.startswith("tag:"):
420 tag_name = "tag:" + tag_name
421 result = {tag_name: tag_value}
422
423 return result
424
425
426 def check_is_instance(module: AnsibleAWSModule) -> bool:
427 device_id = module.params.get("device_id")
428 in_vpc = module.params.get("in_vpc")
429 if not device_id:
430 return False
431 if device_id.startswith("i-"):
432 return True
433
434 if device_id.startswith("eni-") and not in_vpc:
435 raise module.fail_json("If you are specifying an ENI, in_vpc must be true")
436 return False
437
438
439 def ensure_absent(
440 client: Any, module: AnsibleAWSModule, address: Optional[Dict[str, Any]], is_instance: bool
441 ) -> Dict[str, bool]:
442 disassociated = False
443 released = False
444
445 device_id = module.params.get("device_id")
446 release_on_disassociation = module.params.get("release_on_disassociation")
447
448 if address:
449 if device_id:
450 # disassociating address from instance
451 association_id = address_is_associated_with_device(client, address, device_id, is_instance)
452 if association_id:
453 disassociated = True
454 if not module.check_mode:
455 disassociated = disassociate_address(client, association_id=association_id)
456
457 if not device_id or (disassociated and release_on_disassociation):
458 # Release or Release on disassociation
459 released = True
460 if not module.check_mode:
461 released = release_address(client, allocation_id=address["AllocationId"])
462 return {"changed": disassociated or released, "disassociated": disassociated, "released": released}
463
464
465 def ensure_present(
466 client, module: AnsibleAWSModule, address: Optional[Dict[str, Any]], is_instance: bool
467 ) -> Dict[str, Any]:
468 device_id = module.params.get("device_id")
469 private_ip_address = module.params.get("private_ip_address")
470 in_vpc = module.params.get("in_vpc")
471 domain = "vpc" if in_vpc else None
472 reuse_existing_ip_allowed = module.params.get("reuse_existing_ip_allowed")
473 allow_reassociation = module.params.get("allow_reassociation")
474 public_ipv4_pool = module.params.get("public_ipv4_pool")
475 tags = module.params.get("tags")
476 purge_tags = module.params.get("purge_tags")
477 domain_name = module.params.get("domain_name")
478
479 # Tags for *searching* for an EIP.
480 search_tags = generate_tag_dict(module)
481 result = {}
482 changed = False
483
484 # Allocate address
485 if not address:
486 address, changed = allocate_address(
487 client, module.check_mode, search_tags, domain, reuse_existing_ip_allowed, tags, public_ipv4_pool
488 )
489
490 if domain_name is not None:
491 changed, update_reverse_dns_record_result = update_reverse_dns_record_of_eip(
492 client, module, address, domain_name
493 )
494 result.update({"update_reverse_dns_record_result": update_reverse_dns_record_result})
495
496 # Associate address to instance
497 if device_id:
498 # Find instance
499 instance = find_device(client, device_id, is_instance)
500 # Allocate an IP for instance since no public_ip was provided
501 if is_instance and reuse_existing_ip_allowed:
502 if instance["VpcId"] and len(instance["VpcId"]) > 0 and domain is None:
503 raise AnsibleEC2Error(
504 "You must set 'in_vpc' to true to associate an instance with an existing ip in a vpc"
505 )
506
507 # check if the address is already associated to the device
508 association_id = address_is_associated_with_device(client, address, device_id, is_instance)
509 if not association_id:
510 changed = True
511 if not module.check_mode:
512 # Associate address object (provided or allocated) with instance
513 if is_instance:
514 params = {"InstanceId": device_id, "AllowReassociation": allow_reassociation}
515 if address.get("Domain") == "vpc":
516 params["AllocationId"] = address.get("AllocationId")
517 else:
518 params["PublicIp"] = address.get("PublicIp")
519 else:
520 params = {
521 "NetworkInterfaceId": device_id,
522 "AllocationId": address.get("AllocationId"),
523 "AllowReassociation": allow_reassociation,
524 }
525
526 if private_ip_address:
527 params["PrivateIpAddress"] = private_ip_address
528 associate_address(client, **params)
529
530 # Ensure tags
531 if address:
532 changed |= ensure_ec2_tags(
533 client, module, address["AllocationId"], resource_type="elastic-ip", tags=tags, purge_tags=purge_tags
534 )
535 result.update({"public_ip": address["PublicIp"], "allocation_id": address["AllocationId"]})
536
537 result["changed"] = changed
538 return result
539
540
541 def update_reverse_dns_record_of_eip(client, module: AnsibleAWSModule, address, domain_name):
542 if module.check_mode:
543 return True, {}
544
545 current_ptr_record_domain = client.describe_addresses_attribute(
546 AllocationIds=[address["AllocationId"]], Attribute="domain-name"
547 )
548
549 if (
550 current_ptr_record_domain["Addresses"]
551 and current_ptr_record_domain["Addresses"][0]["PtrRecord"] == domain_name + "."
552 ):
553 return False, {"ptr_record": domain_name + "."}
554
555 if len(domain_name) == 0:
556 try:
557 update_reverse_dns_record_result = client.reset_address_attribute(
558 AllocationId=address["AllocationId"], Attribute="domain-name"
559 )
560 changed = True
561 except AnsibleEC2Error as e:
562 module.fail_json_aws_error(e)
563
564 if "ResponseMetadata" in update_reverse_dns_record_result:
565 del update_reverse_dns_record_result["ResponseMetadata"]
566 else:
567 try:
568 update_reverse_dns_record_result = client.modify_address_attribute(
569 AllocationId=address["AllocationId"], DomainName=domain_name
570 )
571 changed = True
572 except AnsibleEC2Error as e:
573 module.fail_json_aws_error(e)
574
575 if "ResponseMetadata" in update_reverse_dns_record_result:
576 del update_reverse_dns_record_result["ResponseMetadata"]
577
578 return changed, camel_dict_to_snake_dict(update_reverse_dns_record_result)
579
580
581 def main():
582 argument_spec = dict(
583 device_id=dict(required=False),
584 domain_name=dict(required=False, type="str"),
585 public_ip=dict(required=False, aliases=["ip"]),
586 state=dict(required=False, default="present", choices=["present", "absent"]),
587 in_vpc=dict(required=False, type="bool", default=False),
588 reuse_existing_ip_allowed=dict(required=False, type="bool", default=False),
589 release_on_disassociation=dict(required=False, type="bool", default=False),
590 allow_reassociation=dict(type="bool", default=False),
591 private_ip_address=dict(),
592 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
593 purge_tags=dict(required=False, type="bool", default=True),
594 tag_name=dict(),
595 tag_value=dict(),
596 public_ipv4_pool=dict(),
597 )
598
599 module = AnsibleAWSModule(
600 argument_spec=argument_spec,
601 supports_check_mode=True,
602 required_by={
603 "private_ip_address": ["device_id"],
604 "tag_value": ["tag_name"],
605 },
606 )
607
608 ec2 = module.client("ec2")
609
610 device_id = module.params.get("device_id")
611 public_ip = module.params.get("public_ip")
612 state = module.params.get("state")
613
614 is_instance = check_is_instance(module)
615
616 try:
617 # Find existing address
618 address = find_address(ec2, public_ip, device_id, is_instance)
619 if state == "present":
620 result = ensure_present(ec2, module, address, is_instance)
621 else:
622 result = ensure_absent(ec2, module, address, is_instance)
623
624 except AnsibleEC2Error as e:
625 module.fail_json_aws_error(e)
626
627 module.exit_json(**result)
628
629
630 if __name__ == "__main__":
631 main()