Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the 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_eni
10 version_added: 1.0.0
11 short_description: Create and optionally attach an Elastic Network Interface (ENI) to an instance
12 description:
13 - Create and optionally attach an Elastic Network Interface (ENI) to an instance.
14 - If O(eni_id) or O(private_ip_address) is provided, the existing ENI (if any) will be modified.
15 - The O(attached) parameter controls the attachment status of the network interface.
16 author:
17 - "Rob White (@wimnat)"
18 - "Mike Healey (@healem)"
19 options:
20 eni_id:
21 description:
22 - The ID of the ENI (to modify).
23 - If O(eni_id=None) and O(state=present), a new ENI will be created.
24 type: str
25 instance_id:
26 description:
27 - Instance ID that you wish to attach ENI to.
28 type: str
29 private_ip_address:
30 description:
31 - Private IP address.
32 type: str
33 subnet_id:
34 description:
35 - ID of subnet in which to create the ENI.
36 type: str
37 description:
38 description:
39 - Optional description of the ENI.
40 type: str
41 security_groups:
42 description:
43 - List of security groups associated with the interface.
44 - Ignored when O(state=absent).
45 type: list
46 elements: str
47 default: []
48 state:
49 description:
50 - Create or delete ENI.
51 default: present
52 choices: [ 'present', 'absent' ]
53 type: str
54 device_index:
55 description:
56 - The index of the device for the network interface attachment on the instance.
57 default: 0
58 type: int
59 attached:
60 description:
61 - Specifies if network interface should be attached or detached from instance. If omitted, attachment status
62 won't change
63 type: bool
64 force_detach:
65 description:
66 - Force detachment of the interface. This applies either when explicitly detaching the interface by setting O(instance_id=None)
67 or when deleting an interface with O(state=absent).
68 default: false
69 type: bool
70 delete_on_termination:
71 description:
72 - Delete the interface when the instance it is attached to is terminated. You can only specify this flag when the
73 interface is being modified, not on creation.
74 required: false
75 type: bool
76 source_dest_check:
77 description:
78 - By default, interfaces perform source/destination checks. NAT instances however need this check to be disabled.
79 You can only specify this flag when the interface is being modified, not on creation.
80 required: false
81 type: bool
82 secondary_private_ip_addresses:
83 description:
84 - A list of IP addresses to assign as secondary IP addresses to the network interface.
85 - This option is mutually exclusive of O(secondary_private_ip_address_count).
86 required: false
87 type: list
88 elements: str
89 purge_secondary_private_ip_addresses:
90 description:
91 - To be used with O(secondary_private_ip_addresses) to determine whether or not to remove any secondary IP addresses other than those specified.
92 - Set O(secondary_private_ip_addresses=[]) to purge all secondary addresses.
93 default: false
94 type: bool
95 secondary_private_ip_address_count:
96 description:
97 - The number of secondary IP addresses to assign to the network interface.
98 - This option is mutually exclusive of O(secondary_private_ip_addresses).
99 required: false
100 type: int
101 allow_reassignment:
102 description:
103 - Indicates whether to allow an IP address that is already assigned to another network interface or instance
104 to be reassigned to the specified network interface.
105 required: false
106 default: false
107 type: bool
108 name:
109 description:
110 - Name for the ENI. This will create a tag with the key V(Name) and the value assigned here.
111 - This can be used in conjunction with O(subnet_id) as another means of identifiying a network interface.
112 - AWS does not enforce unique V(Name) tags, so duplicate names are possible if you configure it that way.
113 If that is the case, you will need to provide other identifying information such as O(private_ip_address) or O(eni_id).
114 required: false
115 type: str
116 extends_documentation_fragment:
117 - amazon.aws.common.modules
118 - amazon.aws.region.modules
119 - amazon.aws.tags
120 - amazon.aws.boto3
121 notes:
122 - This module identifies and ENI based on either the O(eni_id), a combination of O(private_ip_address) and O(subnet_id),
123 or a combination of O(instance_id) and O(device_index). Any of these options will let you specify a particular ENI.
124 - Support for O(tags) and O(purge_tags) was added in release 1.3.0.
125 """
126
127 EXAMPLES = r"""
128 # Note: These examples do not set authentication details, see the AWS Guide for details.
129
130 # Create an ENI. As no security group is defined, ENI will be created in default security group
131 - amazon.aws.ec2_eni:
132 private_ip_address: 172.31.0.20
133 subnet_id: subnet-xxxxxxxx
134 state: present
135
136 # Create an ENI and attach it to an instance
137 - amazon.aws.ec2_eni:
138 instance_id: i-xxxxxxx
139 device_index: 1
140 private_ip_address: 172.31.0.20
141 subnet_id: subnet-xxxxxxxx
142 state: present
143
144 # Create an ENI with two secondary addresses
145 - amazon.aws.ec2_eni:
146 subnet_id: subnet-xxxxxxxx
147 state: present
148 secondary_private_ip_address_count: 2
149
150 # Assign a secondary IP address to an existing ENI
151 # This will purge any existing IPs
152 - amazon.aws.ec2_eni:
153 subnet_id: subnet-xxxxxxxx
154 eni_id: eni-yyyyyyyy
155 state: present
156 secondary_private_ip_addresses:
157 - 172.16.1.1
158
159 # Remove any secondary IP addresses from an existing ENI
160 - amazon.aws.ec2_eni:
161 subnet_id: subnet-xxxxxxxx
162 eni_id: eni-yyyyyyyy
163 state: present
164 secondary_private_ip_address_count: 0
165
166 # Destroy an ENI, detaching it from any instance if necessary
167 - amazon.aws.ec2_eni:
168 eni_id: eni-xxxxxxx
169 force_detach: true
170 state: absent
171
172 # Update an ENI
173 - amazon.aws.ec2_eni:
174 eni_id: eni-xxxxxxx
175 description: "My new description"
176 state: present
177
178 # Update an ENI using name and subnet_id
179 - amazon.aws.ec2_eni:
180 name: eni-20
181 subnet_id: subnet-xxxxxxx
182 description: "My new description"
183 state: present
184
185 # Update an ENI identifying it by private_ip_address and subnet_id
186 - amazon.aws.ec2_eni:
187 subnet_id: subnet-xxxxxxx
188 private_ip_address: 172.16.1.1
189 description: "My new description"
190
191 # Detach an ENI from an instance
192 - amazon.aws.ec2_eni:
193 eni_id: eni-xxxxxxx
194 instance_id: None
195 state: present
196
197 ### Delete an interface on termination
198 # First create the interface
199 - amazon.aws.ec2_eni:
200 instance_id: i-xxxxxxx
201 device_index: 1
202 private_ip_address: 172.31.0.20
203 subnet_id: subnet-xxxxxxxx
204 state: present
205 register: eni
206
207 # Modify the interface to enable the delete_on_terminaton flag
208 - amazon.aws.ec2_eni:
209 eni_id: "{{ eni.interface.id }}"
210 delete_on_termination: true
211 """
212
213
214 RETURN = r"""
215 interface:
216 description: Network interface attributes.
217 returned: when state != absent
218 type: complex
219 contains:
220 attachment:
221 description: The network interface attachment.
222 type: dict
223 sample: {
224 "attach_time": "2024-04-25T20:57:20+00:00",
225 "attachment_id": "eni-attach-0ddce58b341a1846f",
226 "delete_on_termination": true,
227 "device_index": 0,
228 "instance_id": "i-032cb1cceb29250d2",
229 "status": "attached"
230 }
231 description:
232 description: Interface description.
233 type: str
234 sample: Firewall network interface
235 groups:
236 description: Dict of security groups.
237 type: dict
238 sample: { "sg-f8a8a9da": "default" }
239 id:
240 description: Network interface id.
241 type: str
242 sample: "eni-1d889198"
243 mac_address:
244 description: Interface's physical address.
245 type: str
246 sample: "00:00:5E:00:53:23"
247 name:
248 description: The name of the ENI.
249 type: str
250 sample: "my-eni-20"
251 owner_id:
252 description: AWS account id.
253 type: str
254 sample: 812381371
255 private_ip_address:
256 description: Primary ip address of this interface.
257 type: str
258 sample: 10.20.30.40
259 private_ip_addresses:
260 description: List of all private ip addresses associated to this interface.
261 type: list
262 elements: dict
263 sample: [ { "primary_address": true, "private_ip_address": "10.20.30.40" } ]
264 source_dest_check:
265 description: Value of source/dest check flag.
266 type: bool
267 sample: True
268 status:
269 description: Network interface status.
270 type: str
271 sample: "pending"
272 subnet_id:
273 description: Which vpc subnet the interface is bound.
274 type: str
275 sample: subnet-b0a0393c
276 tags:
277 description: The dictionary of tags associated with the ENI.
278 type: dict
279 sample: { "Name": "my-eni", "group": "Finance" }
280 vpc_id:
281 description: Which vpc this network interface is bound.
282 type: str
283 sample: vpc-9a9a9da
284 """
285
286 import time
287 from ipaddress import ip_address
288 from ipaddress import ip_network
289
290 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
291 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import assign_private_ip_addresses
292 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import attach_network_interface
293 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_network_interface
294 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_network_interface
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 describe_subnets
297 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import detach_network_interface
298 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
299 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_ec2_security_group_ids_from_names
300 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_network_interface_attribute
301 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import unassign_private_ip_addresses
302 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
303 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
304 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
305 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
306
307
308 def get_eni_info(interface):
309 # Private addresses
310 private_addresses = []
311 if "PrivateIpAddresses" in interface:
312 for ip in interface["PrivateIpAddresses"]:
313 private_addresses.append({"private_ip_address": ip["PrivateIpAddress"], "primary_address": ip["Primary"]})
314
315 groups = {}
316 if "Groups" in interface:
317 for group in interface["Groups"]:
318 groups[group["GroupId"]] = group["GroupName"]
319
320 interface_info = {
321 "id": interface.get("NetworkInterfaceId"),
322 "subnet_id": interface.get("SubnetId"),
323 "vpc_id": interface.get("VpcId"),
324 "description": interface.get("Description"),
325 "owner_id": interface.get("OwnerId"),
326 "status": interface.get("Status"),
327 "mac_address": interface.get("MacAddress"),
328 "private_ip_address": interface.get("PrivateIpAddress"),
329 "source_dest_check": interface.get("SourceDestCheck"),
330 "groups": groups,
331 "private_ip_addresses": private_addresses,
332 }
333
334 if "TagSet" in interface:
335 tags = boto3_tag_list_to_ansible_dict(interface["TagSet"])
336 if "Name" in tags:
337 interface_info["name"] = tags["Name"]
338 interface_info["tags"] = tags
339
340 if "Attachment" in interface:
341 interface_info["attachment"] = {
342 "attachment_id": interface["Attachment"].get("AttachmentId"),
343 "instance_id": interface["Attachment"].get("InstanceId"),
344 "device_index": interface["Attachment"].get("DeviceIndex"),
345 "status": interface["Attachment"].get("Status"),
346 "attach_time": interface["Attachment"].get("AttachTime"),
347 "delete_on_termination": interface["Attachment"].get("DeleteOnTermination"),
348 }
349
350 return interface_info
351
352
353 def correct_ips(connection, ip_list, module, eni_id):
354 eni = describe_eni(connection, module, eni_id)
355 private_addresses = set()
356 if "PrivateIpAddresses" in eni:
357 for ip in eni["PrivateIpAddresses"]:
358 private_addresses.add(ip["PrivateIpAddress"])
359
360 ip_set = set(ip_list)
361
362 return ip_set.issubset(private_addresses)
363
364
365 def absent_ips(connection, ip_list, module, eni_id):
366 eni = describe_eni(connection, module, eni_id)
367 private_addresses = set()
368 if "PrivateIpAddresses" in eni:
369 for ip in eni["PrivateIpAddresses"]:
370 private_addresses.add(ip["PrivateIpAddress"])
371
372 ip_set = set(ip_list)
373
374 return not ip_set.union(private_addresses)
375
376
377 def correct_ip_count(connection, ip_count, module, eni_id):
378 eni = describe_eni(connection, module, eni_id)
379 private_addresses = set()
380 if "PrivateIpAddresses" in eni:
381 for ip in eni["PrivateIpAddresses"]:
382 private_addresses.add(ip["PrivateIpAddress"])
383
384 return bool(len(private_addresses) == ip_count)
385
386
387 def wait_for(function_pointer, *args):
388 max_wait = 30
389 interval_time = 3
390 current_wait = 0
391 while current_wait < max_wait:
392 time.sleep(interval_time)
393 current_wait += interval_time
394 if function_pointer(*args):
395 break
396
397
398 def create_eni(connection, vpc_id, module):
399 instance_id = module.params.get("instance_id")
400 attached = module.params.get("attached")
401 if instance_id == "None":
402 instance_id = None
403 device_index = module.params.get("device_index")
404 subnet_id = module.params.get("subnet_id")
405 private_ip_address = module.params.get("private_ip_address")
406 description = module.params.get("description")
407 security_groups = get_ec2_security_group_ids_from_names(
408 module.params.get("security_groups"), connection, vpc_id=vpc_id
409 )
410 secondary_private_ip_addresses = module.params.get("secondary_private_ip_addresses")
411 secondary_private_ip_address_count = module.params.get("secondary_private_ip_address_count")
412 changed = False
413
414 tags = module.params.get("tags") or dict()
415 name = module.params.get("name")
416 # Make sure that the 'name' parameter sets the Name tag
417 if name:
418 tags["Name"] = name
419
420 args = {"SubnetId": subnet_id}
421 if private_ip_address:
422 args["PrivateIpAddress"] = private_ip_address
423 if description:
424 args["Description"] = description
425 if len(security_groups) > 0:
426 args["Groups"] = security_groups
427 if tags:
428 args["TagSpecifications"] = boto3_tag_specifications(tags, types="network-interface")
429
430 # check if provided private_ip_address is within the subnet's address range
431 if private_ip_address:
432 try:
433 cidr_block = describe_subnets(connection, SubnetIds=[str(subnet_id)])[0]["CidrBlock"]
434 except AnsibleEC2Error as e:
435 module.fail_json_aws_error(e)
436 valid_private_ip = ip_address(private_ip_address) in ip_network(cidr_block)
437 if not valid_private_ip:
438 module.fail_json(
439 changed=False,
440 msg="Error: cannot create ENI - Address does not fall within the subnet's address range.",
441 )
442 if module.check_mode:
443 module.exit_json(changed=True, msg="Would have created ENI if not in check mode.")
444
445 try:
446 eni = create_network_interface(connection, **args)
447 except AnsibleEC2Error as e:
448 module.fail_json_aws_error(e)
449 # Once we have an ID make sure we're always modifying the same object
450 eni_id = eni["NetworkInterfaceId"]
451 wait_for_resource_state(connection, module, "network_interface_available", NetworkInterfaceIds=[eni_id])
452
453 if attached and instance_id is not None:
454 try:
455 attach_network_interface(
456 connection,
457 InstanceId=instance_id,
458 DeviceIndex=device_index,
459 NetworkInterfaceId=eni["NetworkInterfaceId"],
460 )
461 except AnsibleEC2Error as e:
462 delete_network_interface(connection, eni_id)
463 module.fail_json_aws_error(e)
464 wait_for_resource_state(connection, module, "network_interface_attached", NetworkInterfaceIds=[eni_id])
465
466 if secondary_private_ip_address_count is not None:
467 try:
468 assign_private_ip_addresses(
469 connection,
470 NetworkInterfaceId=eni["NetworkInterfaceId"],
471 SecondaryPrivateIpAddressCount=secondary_private_ip_address_count,
472 )
473 wait_for(correct_ip_count, connection, secondary_private_ip_address_count, module, eni_id)
474 except AnsibleEC2Error as e:
475 delete_network_interface(connection, eni_id)
476 module.fail_json_aws_error(e)
477
478 if secondary_private_ip_addresses is not None:
479 try:
480 assign_private_ip_addresses(
481 connection,
482 NetworkInterfaceId=eni["NetworkInterfaceId"],
483 PrivateIpAddresses=secondary_private_ip_addresses,
484 )
485 wait_for(correct_ips, connection, secondary_private_ip_addresses, module, eni_id)
486 except AnsibleEC2Error as e:
487 delete_network_interface(connection, eni_id)
488 module.fail_json_aws_error(e)
489
490 # Refresh the eni data
491 eni = describe_eni(connection, module, eni_id)
492 changed = True
493
494 module.exit_json(changed=changed, interface=get_eni_info(eni))
495
496
497 def modify_eni(connection, module, eni):
498 instance_id = module.params.get("instance_id")
499 attached = module.params.get("attached")
500 device_index = module.params.get("device_index")
501 description = module.params.get("description")
502 security_groups = module.params.get("security_groups")
503 source_dest_check = module.params.get("source_dest_check")
504 delete_on_termination = module.params.get("delete_on_termination")
505 secondary_private_ip_addresses = module.params.get("secondary_private_ip_addresses")
506 purge_secondary_private_ip_addresses = module.params.get("purge_secondary_private_ip_addresses")
507 secondary_private_ip_address_count = module.params.get("secondary_private_ip_address_count")
508 allow_reassignment = module.params.get("allow_reassignment")
509 changed = False
510 tags = module.params.get("tags")
511 name = module.params.get("name")
512 purge_tags = module.params.get("purge_tags")
513
514 eni = uniquely_find_eni(connection, module, eni)
515 eni_id = eni["NetworkInterfaceId"]
516
517 try:
518 if description is not None:
519 if "Description" not in eni or eni["Description"] != description:
520 if not module.check_mode:
521 modify_network_interface_attribute(
522 connection, NetworkInterfaceId=eni_id, Description={"Value": description}
523 )
524 changed = True
525 if len(security_groups) > 0:
526 groups = get_ec2_security_group_ids_from_names(security_groups, connection, vpc_id=eni["VpcId"])
527 if sorted(get_sec_group_list(eni["Groups"])) != sorted(groups):
528 if not module.check_mode:
529 modify_network_interface_attribute(connection, NetworkInterfaceId=eni_id, Groups=groups)
530 changed = True
531 if source_dest_check is not None:
532 if "SourceDestCheck" not in eni or eni["SourceDestCheck"] != source_dest_check:
533 if not module.check_mode:
534 modify_network_interface_attribute(
535 connection, NetworkInterfaceId=eni_id, SourceDestCheck={"Value": source_dest_check}
536 )
537 changed = True
538 if delete_on_termination is not None and "Attachment" in eni:
539 if eni["Attachment"]["DeleteOnTermination"] is not delete_on_termination:
540 if not module.check_mode:
541 modify_network_interface_attribute(
542 connection,
543 NetworkInterfaceId=eni_id,
544 Attachment={
545 "AttachmentId": eni["Attachment"]["AttachmentId"],
546 "DeleteOnTermination": delete_on_termination,
547 },
548 )
549 if delete_on_termination:
550 waiter = "network_interface_delete_on_terminate"
551 else:
552 waiter = "network_interface_no_delete_on_terminate"
553 wait_for_resource_state(connection, module, waiter, NetworkInterfaceIds=[eni_id])
554 changed = True
555
556 current_secondary_addresses = []
557 if "PrivateIpAddresses" in eni:
558 current_secondary_addresses = [i["PrivateIpAddress"] for i in eni["PrivateIpAddresses"] if not i["Primary"]]
559
560 if secondary_private_ip_addresses is not None:
561 secondary_addresses_to_remove = list(set(current_secondary_addresses) - set(secondary_private_ip_addresses))
562 if secondary_addresses_to_remove and purge_secondary_private_ip_addresses:
563 if not module.check_mode:
564 unassign_private_ip_addresses(
565 connection,
566 NetworkInterfaceId=eni_id,
567 PrivateIpAddresses=list(set(current_secondary_addresses) - set(secondary_private_ip_addresses)),
568 )
569 wait_for(absent_ips, connection, secondary_addresses_to_remove, module, eni_id)
570 changed = True
571 secondary_addresses_to_add = list(set(secondary_private_ip_addresses) - set(current_secondary_addresses))
572 if secondary_addresses_to_add:
573 if not module.check_mode:
574 assign_private_ip_addresses(
575 connection,
576 NetworkInterfaceId=eni_id,
577 PrivateIpAddresses=secondary_addresses_to_add,
578 AllowReassignment=allow_reassignment,
579 )
580 wait_for(correct_ips, connection, secondary_addresses_to_add, module, eni_id)
581 changed = True
582
583 if secondary_private_ip_address_count is not None:
584 current_secondary_address_count = len(current_secondary_addresses)
585 if secondary_private_ip_address_count > current_secondary_address_count:
586 if not module.check_mode:
587 assign_private_ip_addresses(
588 connection,
589 NetworkInterfaceId=eni_id,
590 SecondaryPrivateIpAddressCount=(
591 secondary_private_ip_address_count - current_secondary_address_count
592 ),
593 AllowReassignment=allow_reassignment,
594 )
595 wait_for(correct_ip_count, connection, secondary_private_ip_address_count, module, eni_id)
596 changed = True
597 elif secondary_private_ip_address_count < current_secondary_address_count:
598 # How many of these addresses do we want to remove
599 if not module.check_mode:
600 secondary_addresses_to_remove_count = (
601 current_secondary_address_count - secondary_private_ip_address_count
602 )
603 unassign_private_ip_addresses(
604 connection,
605 NetworkInterfaceId=eni_id,
606 PrivateIpAddresses=current_secondary_addresses[:secondary_addresses_to_remove_count],
607 )
608 wait_for(correct_ip_count, connection, secondary_private_ip_address_count, module, eni_id)
609 changed = True
610
611 if attached is True:
612 if "Attachment" in eni and eni["Attachment"]["InstanceId"] != instance_id:
613 if not module.check_mode:
614 detach_eni(connection, eni, module)
615 attach_network_interface(
616 connection,
617 InstanceId=instance_id,
618 DeviceIndex=device_index,
619 NetworkInterfaceId=eni_id,
620 )
621 wait_for_resource_state(
622 connection, module, "network_interface_attached", NetworkInterfaceIds=[eni_id]
623 )
624 changed = True
625 if "Attachment" not in eni:
626 if not module.check_mode:
627 attach_network_interface(
628 connection,
629 InstanceId=instance_id,
630 DeviceIndex=device_index,
631 NetworkInterfaceId=eni_id,
632 )
633 wait_for_resource_state(
634 connection, module, "network_interface_attached", NetworkInterfaceIds=[eni_id]
635 )
636 changed = True
637
638 elif attached is False:
639 changed |= detach_eni(connection, eni, module)
640 wait_for_resource_state(connection, module, "network_interface_available", NetworkInterfaceIds=[eni_id])
641
642 changed |= manage_tags(connection, module, eni, name, tags, purge_tags)
643
644 except AnsibleEC2Error as e:
645 module.fail_json_aws_error(e)
646
647 eni = describe_eni(connection, module, eni_id)
648 if module.check_mode and changed:
649 module.exit_json(
650 changed=changed, msg=f"Would have modified ENI: {eni['NetworkInterfaceId']} if not in check mode"
651 )
652 module.exit_json(changed=changed, interface=get_eni_info(eni))
653
654
655 def delete_eni(connection, module):
656 eni = uniquely_find_eni(connection, module)
657 if not eni:
658 module.exit_json(changed=False)
659
660 if module.check_mode:
661 module.exit_json(changed=True, msg="Would have deleted ENI if not in check mode.")
662
663 eni_id = eni["NetworkInterfaceId"]
664 force_detach = module.params.get("force_detach")
665
666 try:
667 if force_detach is True:
668 if "Attachment" in eni:
669 detach_network_interface(
670 connection,
671 attachment_id=eni["Attachment"]["AttachmentId"],
672 force=True,
673 )
674 wait_for_resource_state(
675 connection,
676 module,
677 "network_interface_available",
678 delay=5,
679 max_attempts=80,
680 NetworkInterfaceIds=[eni_id],
681 )
682 changed = delete_network_interface(connection, eni_id)
683 else:
684 changed = delete_network_interface(connection, eni_id)
685
686 module.exit_json(changed=changed)
687 except AnsibleEC2Error as e:
688 module.fail_json_aws_error(e)
689
690
691 def detach_eni(connection, eni, module):
692 if module.check_mode:
693 module.exit_json(changed=True, msg="Would have detached ENI if not in check mode.")
694
695 eni_id = eni["NetworkInterfaceId"]
696
697 force_detach = module.params.get("force_detach")
698 if "Attachment" in eni:
699 detach_network_interface(
700 connection,
701 attachment_id=eni["Attachment"]["AttachmentId"],
702 force=force_detach,
703 )
704 wait_for_resource_state(
705 connection, module, "network_interface_available", delay=5, max_attempts=80, NetworkInterfaceIds=[eni_id]
706 )
707 return True
708
709 return False
710
711
712 def describe_eni(connection, module, eni_id):
713 try:
714 result = None
715 enis = describe_network_interfaces(connection, NetworkInterfaceIds=[eni_id])
716 if enis:
717 result = enis[0]
718 return result
719 except AnsibleEC2Error as e:
720 module.fail_json_aws_error(e)
721
722
723 def uniquely_find_eni(connection, module, eni=None):
724 if eni:
725 # In the case of create, eni_id will not be a param but we can still get the eni_id after creation
726 if "NetworkInterfaceId" in eni:
727 eni_id = eni["NetworkInterfaceId"]
728 else:
729 eni_id = None
730 else:
731 eni_id = module.params.get("eni_id")
732
733 private_ip_address = module.params.get("private_ip_address")
734 subnet_id = module.params.get("subnet_id")
735 instance_id = module.params.get("instance_id")
736 device_index = module.params.get("device_index")
737 attached = module.params.get("attached")
738 name = module.params.get("name")
739
740 filters = []
741
742 # proceed only if we're unequivocally specifying an ENI
743 if eni_id is None and private_ip_address is None and (instance_id is None and device_index is None):
744 return None
745
746 if eni_id:
747 filters.append({"Name": "network-interface-id", "Values": [eni_id]})
748
749 if private_ip_address and subnet_id and not filters:
750 filters.append({"Name": "private-ip-address", "Values": [private_ip_address]})
751 filters.append({"Name": "subnet-id", "Values": [subnet_id]})
752
753 if not attached and instance_id and device_index and not filters:
754 filters.append({"Name": "attachment.instance-id", "Values": [instance_id]})
755 filters.append({"Name": "attachment.device-index", "Values": [str(device_index)]})
756
757 if name and subnet_id and not filters:
758 filters.append({"Name": "tag:Name", "Values": [name]})
759 filters.append({"Name": "subnet-id", "Values": [subnet_id]})
760
761 if not filters:
762 return None
763
764 try:
765 result = None
766 enis = describe_network_interfaces(connection, Filters=filters)
767 if len(enis) == 1:
768 result = enis[0]
769 return result
770 except AnsibleEC2Error as e:
771 module.fail_json_aws_error(e)
772
773
774 def get_sec_group_list(groups):
775 # Build list of remote security groups
776 remote_security_groups = []
777 for group in groups:
778 remote_security_groups.append(group["GroupId"])
779
780 return remote_security_groups
781
782
783 def _get_vpc_id(connection, module, subnet_id):
784 try:
785 return describe_subnets(connection, SubnetIds=[subnet_id])[0]["VpcId"]
786 except AnsibleEC2Error as e:
787 module.fail_json_aws_error(e)
788
789
790 def manage_tags(connection, module, eni, name, tags, purge_tags):
791 # Do not purge tags unless tags is not None
792 if tags is None:
793 purge_tags = False
794 tags = {}
795
796 if name:
797 tags["Name"] = name
798
799 eni_id = eni["NetworkInterfaceId"]
800
801 changed = ensure_ec2_tags(connection, module, eni_id, tags=tags, purge_tags=purge_tags)
802 return changed
803
804
805 def main():
806 argument_spec = dict(
807 eni_id=dict(default=None, type="str"),
808 instance_id=dict(default=None, type="str"),
809 private_ip_address=dict(type="str"),
810 subnet_id=dict(type="str"),
811 description=dict(type="str"),
812 security_groups=dict(default=[], type="list", elements="str"),
813 device_index=dict(default=0, type="int"),
814 state=dict(default="present", choices=["present", "absent"]),
815 force_detach=dict(default="no", type="bool"),
816 source_dest_check=dict(default=None, type="bool"),
817 delete_on_termination=dict(default=None, type="bool"),
818 secondary_private_ip_addresses=dict(default=None, type="list", elements="str"),
819 purge_secondary_private_ip_addresses=dict(default=False, type="bool"),
820 secondary_private_ip_address_count=dict(default=None, type="int"),
821 allow_reassignment=dict(default=False, type="bool"),
822 attached=dict(default=None, type="bool"),
823 name=dict(default=None, type="str"),
824 tags=dict(type="dict", aliases=["resource_tags"]),
825 purge_tags=dict(default=True, type="bool"),
826 )
827
828 module = AnsibleAWSModule(
829 argument_spec=argument_spec,
830 mutually_exclusive=[["secondary_private_ip_addresses", "secondary_private_ip_address_count"]],
831 required_if=(
832 [
833 ("attached", True, ["instance_id"]),
834 ("purge_secondary_private_ip_addresses", True, ["secondary_private_ip_addresses"]),
835 ]
836 ),
837 supports_check_mode=True,
838 )
839
840 connection = module.client("ec2")
841 state = module.params.get("state")
842
843 if state == "present":
844 eni = uniquely_find_eni(connection, module)
845 if eni is None:
846 subnet_id = module.params.get("subnet_id")
847 if subnet_id is None:
848 module.fail_json(msg="subnet_id is required when creating a new ENI")
849
850 vpc_id = _get_vpc_id(connection, module, subnet_id)
851 create_eni(connection, vpc_id, module)
852 else:
853 modify_eni(connection, module, eni)
854
855 elif state == "absent":
856 delete_eni(connection, module)
857
858
859 if __name__ == "__main__":
860 main()