Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_vpc_net.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_vpc_net
10 version_added: 1.0.0
11 short_description: Configure AWS Virtual Private Clouds
12 description:
13 - Create, modify, and terminate AWS Virtual Private Clouds (VPCs).
14 author:
15 - Jonathan Davila (@defionscode)
16 - Sloane Hertel (@s-hertel)
17 options:
18 name:
19 description:
20 - The name to give your VPC. This is used in combination with O(cidr_block)
21 to determine if a VPC already exists.
22 - The value of O(name) overrides any value set for V(Name) in the O(tags)
23 parameter.
24 - At least one of O(name) and O(vpc_id) must be specified.
25 - O(name) must be specified when creating a new VPC.
26 type: str
27 vpc_id:
28 version_added: 4.0.0
29 description:
30 - The ID of the VPC.
31 - At least one of O(name) and O(vpc_id) must be specified.
32 - At least one of O(name) and O(cidr_block) must be specified.
33 type: str
34 cidr_block:
35 description:
36 - The primary CIDR of the VPC.
37 - The first in the list will be used as the primary CIDR
38 and is used in conjunction with O(name) to ensure idempotence.
39 - Required when O(vpc_id) is not set.
40 type: list
41 elements: str
42 ipv6_cidr:
43 description:
44 - Request an Amazon-provided IPv6 CIDR block with /56 prefix length. You cannot specify the range of IPv6 addresses,
45 or the size of the CIDR block.
46 - Default value is V(false) when creating a new VPC.
47 type: bool
48 purge_cidrs:
49 description:
50 - Remove CIDRs that are associated with the VPC and are not specified in O(cidr_block).
51 default: false
52 type: bool
53 tenancy:
54 description:
55 - Whether to be V(default) or V(dedicated) tenancy.
56 - This cannot be changed after the VPC has been created.
57 default: default
58 choices: [ 'default', 'dedicated' ]
59 type: str
60 dns_support:
61 description:
62 - Whether to enable AWS DNS support.
63 - Default value is V(true) when creating a new VPC.
64 type: bool
65 dns_hostnames:
66 description:
67 - Whether to enable AWS hostname support.
68 - Default value is V(true) when creating a new VPC.
69 type: bool
70 dhcp_opts_id:
71 description:
72 - The id of the DHCP options to use for this VPC.
73 type: str
74 state:
75 description:
76 - The state of the VPC. Either absent or present.
77 default: present
78 choices: [ 'present', 'absent' ]
79 type: str
80 multi_ok:
81 description:
82 - By default the module will not create another VPC if there is another VPC with the same name and CIDR block.
83 Specify O(multi_ok=true) if you want duplicate VPCs created.
84 type: bool
85 default: false
86 extends_documentation_fragment:
87 - amazon.aws.common.modules
88 - amazon.aws.region.modules
89 - amazon.aws.tags
90 - amazon.aws.boto3
91 """
92
93 EXAMPLES = r"""
94 # Note: These examples do not set authentication details, see the AWS Guide for details.
95
96 - name: create a VPC with dedicated tenancy and a couple of tags
97 amazon.aws.ec2_vpc_net:
98 name: Module_dev2
99 cidr_block: 10.10.0.0/16
100 region: us-east-1
101 tags:
102 module: ec2_vpc_net
103 this: works
104 tenancy: dedicated
105
106 - name: create a VPC with dedicated tenancy and request an IPv6 CIDR
107 amazon.aws.ec2_vpc_net:
108 name: Module_dev2
109 cidr_block: 10.10.0.0/16
110 ipv6_cidr: true
111 region: us-east-1
112 tenancy: dedicated
113
114 - name: Delete an existing VPC
115 amazon.aws.ec2_vpc_net:
116 vpc_id: vpc-0123456789abcdef0
117 state: absent
118 """
119
120 RETURN = r"""
121 vpc:
122 description: Info about the VPC that was created or deleted.
123 returned: always
124 type: complex
125 contains:
126 cidr_block:
127 description: The CIDR of the VPC.
128 returned: always
129 type: str
130 sample: 10.0.0.0/16
131 cidr_block_association_set:
132 description: IPv4 CIDR blocks associated with the VPC.
133 returned: success
134 type: list
135 sample:
136 "cidr_block_association_set": [
137 {
138 "association_id": "vpc-cidr-assoc-97aeeefd",
139 "cidr_block": "10.0.0.0/24",
140 "cidr_block_state": {
141 "state": "associated"
142 }
143 }
144 ]
145 dhcp_options_id:
146 description: The id of the DHCP options associated with this VPC.
147 returned: always
148 type: str
149 sample: dopt-12345678
150 id:
151 description: VPC resource id.
152 returned: always
153 type: str
154 sample: vpc-12345678
155 name:
156 description: The Name tag of the VPC.
157 returned: When the Name tag has been set on the VPC
158 type: str
159 sample: MyVPC
160 version_added: 4.0.0
161 instance_tenancy:
162 description: Indicates whether VPC uses default or dedicated tenancy.
163 returned: always
164 type: str
165 sample: default
166 ipv6_cidr_block_association_set:
167 description: IPv6 CIDR blocks associated with the VPC.
168 returned: success
169 type: list
170 sample:
171 "ipv6_cidr_block_association_set": [
172 {
173 "association_id": "vpc-cidr-assoc-97aeeefd",
174 "ipv6_cidr_block": "2001:db8::/56",
175 "ipv6_cidr_block_state": {
176 "state": "associated"
177 }
178 }
179 ]
180 is_default:
181 description: Indicates whether this is the default VPC.
182 returned: always
183 type: bool
184 sample: false
185 state:
186 description: State of the VPC.
187 returned: always
188 type: str
189 sample: available
190 tags:
191 description: Tags attached to the VPC, includes name.
192 returned: always
193 type: complex
194 contains:
195 Name:
196 description: Name tag for the VPC.
197 returned: always
198 type: str
199 sample: pk_vpc4
200 owner_id:
201 description: The AWS account which owns the VPC.
202 returned: always
203 type: str
204 sample: 123456789012
205 """
206
207 from time import sleep
208 from time import time
209 from typing import Any
210 from typing import Dict
211 from typing import List
212 from typing import Optional
213
214 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
215 from ansible.module_utils.common.network import to_subnet
216
217 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
218 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import associate_dhcp_options
219 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import associate_vpc_cidr_block
220 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_vpc
221 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_vpc
222 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_vpc_attribute
223 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_vpcs
224 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import disassociate_vpc_cidr_block
225 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
226 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_vpc_attribute
227 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
228 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
229 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
230 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
231 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
232 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
233
234
235 def get_vpc_id(connection, module: AnsibleAWSModule) -> Optional[str]:
236 """Returns None or a vpc object depending on the existence of a VPC. When supplied
237 with a CIDR, it will check for matching tags to determine if it is a match
238 otherwise it will assume the VPC does not exist and thus return None.
239 """
240 name = module.params.get("name")
241 cidr_block = module.params.get("cidr_block")
242 multi_ok = module.params.get("multi_ok")
243 vpc_filters = ansible_dict_to_boto3_filter_list({"tag:Name": name, "cidr-block": cidr_block})
244 matching_vpcs = describe_vpcs(connection, Filters=vpc_filters)
245 # If an exact matching using a list of CIDRs isn't found, check for a match with the first CIDR as is documented for C(cidr_block)
246 if not matching_vpcs:
247 vpc_filters = ansible_dict_to_boto3_filter_list({"tag:Name": name, "cidr-block": [cidr_block[0]]})
248 matching_vpcs = describe_vpcs(connection, Filters=vpc_filters)
249
250 vpc_id = None
251 if not multi_ok and matching_vpcs:
252 if len(matching_vpcs) > 1:
253 module.fail_json(
254 msg=(
255 f"Currently there are {len(matching_vpcs)} VPCs that have the same name and CIDR block you specified."
256 " If you would like to create the VPC anyway please pass True to the multi_ok param."
257 )
258 )
259 vpc_id = matching_vpcs[0]["VpcId"]
260 return vpc_id
261
262
263 def get_vpc(module: AnsibleAWSModule, connection, vpc_id: str) -> Dict[str, Any]:
264 wait_for_resource_state(connection, module, "vpc_available", VpcIds=[vpc_id])
265 return describe_vpcs(connection, VpcIds=[vpc_id])[0]
266
267
268 def update_vpc_tags(connection, module, vpc_id, tags, name, purge_tags):
269 # Name is a tag rather than a direct parameter, we need to inject 'Name'
270 # into tags, but since tags isn't explicitly passed we'll treat it not being
271 # set as purge_tags == False
272 if name:
273 if purge_tags and tags is None:
274 purge_tags = False
275 tags = tags or {}
276 tags.update({"Name": name})
277
278 if tags is None:
279 return False
280
281 changed = ensure_ec2_tags(connection, module, vpc_id, tags=tags, purge_tags=purge_tags)
282 if not changed or module.check_mode:
283 return changed
284
285 return True
286
287
288 def update_dhcp_opts(connection, module: AnsibleAWSModule, vpc_obj: Dict[str, Any], dhcp_id: Optional[str]) -> bool:
289 if dhcp_id is None:
290 return False
291 if vpc_obj["DhcpOptionsId"] == dhcp_id:
292 return False
293 if module.check_mode:
294 return True
295
296 return associate_dhcp_options(connection, vpc_id=vpc_obj["VpcId"], dhcp_options_id=dhcp_id)
297
298
299 def create_vpc_net(
300 connection,
301 module: AnsibleAWSModule,
302 cidr_block: List[str],
303 tenancy,
304 tags: Dict[str, str],
305 ipv6_cidr: bool,
306 name: Optional[str],
307 ) -> Dict[str, Any]:
308 if module.check_mode:
309 module.exit_json(changed=True, msg="VPC would be created if not in check mode")
310
311 create_args = dict(
312 CidrBlock=cidr_block,
313 InstanceTenancy=tenancy,
314 )
315
316 if name:
317 tags = tags or {}
318 tags["Name"] = name
319 if tags:
320 create_args["TagSpecifications"] = boto3_tag_specifications(tags, "vpc")
321
322 # Defaults to False (including None)
323 if ipv6_cidr:
324 create_args["AmazonProvidedIpv6CidrBlock"] = True
325
326 vpc_obj = create_vpc(connection, **create_args)
327
328 # Wait up to 30 seconds for vpc to exist and for state 'available'
329 for waiter_name in ("vpc_exists", "vpc_available"):
330 wait_for_resource_state(connection, module, waiter_name, max_attempts=30, VpcIds=[vpc_obj["VpcId"]])
331
332 return vpc_obj
333
334
335 def wait_for_vpc_attribute(connection, module, vpc_id, attribute, expected_value):
336 if expected_value is None:
337 return
338 if module.check_mode:
339 return
340
341 start_time = time()
342 updated = False
343 while time() < start_time + 300:
344 current_value = describe_vpc_attribute(connection, attribute=attribute, vpc_id=vpc_id)[
345 f"{attribute[0].upper()}{attribute[1:]}"
346 ]["Value"]
347 if current_value != expected_value:
348 sleep(3)
349 else:
350 updated = True
351 break
352 if not updated:
353 module.fail_json(msg=f"Failed to wait for {attribute} to be updated")
354
355
356 def wait_for_vpc_ipv6_state(module, connection, vpc_id, ipv6_assoc_state):
357 """
358 If ipv6_assoc_state is True, wait for VPC to be associated with at least one Amazon-provided IPv6 CIDR block.
359 If ipv6_assoc_state is False, wait for VPC to be dissociated from all Amazon-provided IPv6 CIDR blocks.
360 """
361
362 if ipv6_assoc_state is None:
363 return
364 if module.check_mode:
365 return
366
367 start_time = time()
368 criteria_match = False
369 while time() < start_time + 300:
370 current_value = get_vpc(module, connection, vpc_id)
371 if current_value:
372 ipv6_set = current_value.get("Ipv6CidrBlockAssociationSet")
373 # "ipv6_cidr": false and no Ipv6CidrBlockAssociationSet
374 if not ipv6_set and not ipv6_assoc_state:
375 return
376 if ipv6_set:
377 if ipv6_assoc_state:
378 # At least one 'Amazon' IPv6 CIDR block must be associated.
379 for val in ipv6_set:
380 if (
381 val.get("Ipv6Pool") == "Amazon"
382 and val.get("Ipv6CidrBlockState").get("State") == "associated"
383 ):
384 criteria_match = True
385 break
386 if criteria_match:
387 break
388 else:
389 # All 'Amazon' IPv6 CIDR blocks must be disassociated.
390 expected_count = sum([(val.get("Ipv6Pool") == "Amazon") for val in ipv6_set])
391 actual_count = sum(
392 [
393 (
394 val.get("Ipv6Pool") == "Amazon"
395 and val.get("Ipv6CidrBlockState").get("State") == "disassociated"
396 )
397 for val in ipv6_set
398 ]
399 )
400 if actual_count == expected_count:
401 criteria_match = True
402 break
403 sleep(3)
404 if not criteria_match:
405 module.fail_json(msg="Failed to wait for IPv6 CIDR association")
406
407
408 def get_cidr_network_bits(module, cidr_block):
409 if cidr_block is None:
410 return None
411
412 fixed_cidrs = []
413 for cidr in cidr_block:
414 split_addr = cidr.split("/")
415 if len(split_addr) == 2:
416 # this_ip is a IPv4 CIDR that may or may not have host bits set
417 # Get the network bits.
418 valid_cidr = to_subnet(split_addr[0], split_addr[1])
419 if cidr != valid_cidr:
420 module.warn(
421 f"One of your CIDR addresses ({cidr}) has host bits set. To get rid of this warning, check the"
422 f" network mask and make sure that only network bits are set: {valid_cidr}."
423 )
424 fixed_cidrs.append(valid_cidr)
425 else:
426 # let AWS handle invalid CIDRs
427 fixed_cidrs.append(cidr)
428 return fixed_cidrs
429
430
431 def update_ipv6_cidrs(connection, module, vpc_obj, vpc_id, ipv6_cidr):
432 if ipv6_cidr is None:
433 return False
434
435 # Fetch current state from vpc_object
436 current_ipv6_cidr = False
437 if "Ipv6CidrBlockAssociationSet" in vpc_obj.keys():
438 for ipv6_assoc in vpc_obj["Ipv6CidrBlockAssociationSet"]:
439 if ipv6_assoc["Ipv6Pool"] == "Amazon" and ipv6_assoc["Ipv6CidrBlockState"]["State"] in [
440 "associated",
441 "associating",
442 ]:
443 current_ipv6_cidr = True
444 break
445
446 if ipv6_cidr == current_ipv6_cidr:
447 return False
448
449 if module.check_mode:
450 return True
451
452 # There's no block associated, and we want one to be associated
453 if ipv6_cidr:
454 associate_vpc_cidr_block(connection, vpc_id=vpc_id, AmazonProvidedIpv6CidrBlock=ipv6_cidr)
455 else:
456 for ipv6_assoc in vpc_obj["Ipv6CidrBlockAssociationSet"]:
457 if ipv6_assoc["Ipv6Pool"] == "Amazon" and ipv6_assoc["Ipv6CidrBlockState"]["State"] in [
458 "associated",
459 "associating",
460 ]:
461 disassociate_vpc_cidr_block(connection, association_id=ipv6_assoc["AssociationId"])
462 return True
463
464
465 def update_cidrs(connection, module, vpc_obj, cidr_block, purge_cidrs):
466 if not cidr_block:
467 return False, None
468
469 associated_cidrs = dict(
470 (cidr["CidrBlock"], cidr["AssociationId"])
471 for cidr in vpc_obj.get("CidrBlockAssociationSet", [])
472 if cidr["CidrBlockState"]["State"] not in ["disassociating", "disassociated"]
473 )
474
475 current_cidrs = set(associated_cidrs.keys())
476 desired_cidrs = set(cidr_block)
477 if not purge_cidrs:
478 desired_cidrs = desired_cidrs.union(current_cidrs)
479
480 cidrs_to_add = list(desired_cidrs.difference(current_cidrs))
481 cidrs_to_remove = list(current_cidrs.difference(desired_cidrs))
482
483 if not cidrs_to_add and not cidrs_to_remove:
484 return False, None
485
486 if not module.check_mode:
487 for cidr in cidrs_to_add:
488 try:
489 associate_vpc_cidr_block(connection, vpc_id=vpc_obj["VpcId"], CidrBlock=cidr)
490 except AnsibleEC2Error as e:
491 module.fail_json_aws(e, f"Unable to associate CIDR {cidr}.")
492
493 for cidr in cidrs_to_remove:
494 try:
495 disassociate_vpc_cidr_block(connection, associated_cidrs[cidr])
496 except AnsibleEC2Error as e:
497 module.fail_json_aws(
498 e,
499 (
500 f"Unable to disassociate {associated_cidrs[cidr]}. You must detach or delete all gateways and resources"
501 " that are associated with the CIDR block before you can disassociate it."
502 ),
503 )
504 return True, list(desired_cidrs)
505
506
507 def update_dns_enabled(connection, module, vpc_id, dns_support):
508 if dns_support is None:
509 return False
510
511 current_dns_enabled = describe_vpc_attribute(connection, attribute="enableDnsSupport", vpc_id=vpc_id)[
512 "EnableDnsSupport"
513 ]["Value"]
514 if current_dns_enabled == dns_support:
515 return False
516
517 if module.check_mode:
518 return True
519
520 modify_vpc_attribute(connection, vpc_id=vpc_id, EnableDnsSupport={"Value": dns_support})
521 return True
522
523
524 def update_dns_hostnames(connection, module, vpc_id, dns_hostnames):
525 if dns_hostnames is None:
526 return False
527
528 current_dns_hostnames = describe_vpc_attribute(connection, attribute="enableDnsHostnames", vpc_id=vpc_id)[
529 "EnableDnsHostnames"
530 ]["Value"]
531 if current_dns_hostnames == dns_hostnames:
532 return False
533
534 if module.check_mode:
535 return True
536
537 modify_vpc_attribute(connection, vpc_id=vpc_id, EnableDnsHostnames={"Value": dns_hostnames})
538 return True
539
540
541 def wait_for_updates(connection, module, vpc_id, ipv6_cidr, expected_cidrs, dns_support, dns_hostnames, tags, dhcp_id):
542 if module.check_mode:
543 return
544
545 if expected_cidrs:
546 wait_for_resource_state(
547 connection,
548 module,
549 "vpc_available",
550 VpcIds=[vpc_id],
551 Filters=[{"Name": "cidr-block-association.cidr-block", "Values": expected_cidrs}],
552 )
553 wait_for_vpc_ipv6_state(module, connection, vpc_id, ipv6_cidr)
554
555 if tags is not None:
556 tag_list = ansible_dict_to_boto3_tag_list(tags)
557 filters = [{"Name": f"tag:{t['Key']}", "Values": [t["Value"]]} for t in tag_list]
558 wait_for_resource_state(connection, module, "vpc_available", VpcIds=[vpc_id], Filters=filters)
559
560 wait_for_vpc_attribute(connection, module, vpc_id, "enableDnsSupport", dns_support)
561 wait_for_vpc_attribute(connection, module, vpc_id, "enableDnsHostnames", dns_hostnames)
562
563 if dhcp_id is not None:
564 # Wait for DhcpOptionsId to be updated
565 filters = [{"Name": "dhcp-options-id", "Values": [dhcp_id]}]
566 wait_for_resource_state(connection, module, "vpc_available", VpcIds=[vpc_id], Filters=filters)
567
568 return
569
570
571 def ensure_present(connection, module: AnsibleAWSModule, vpc_id: Optional[str]) -> None:
572 name = module.params.get("name")
573 cidr_block = module.params.get("cidr_block")
574 ipv6_cidr = module.params.get("ipv6_cidr")
575 purge_cidrs = module.params.get("purge_cidrs")
576 tenancy = module.params.get("tenancy")
577 dns_support = module.params.get("dns_support")
578 dns_hostnames = module.params.get("dns_hostnames")
579 dhcp_id = module.params.get("dhcp_opts_id")
580 tags = module.params.get("tags")
581 purge_tags = module.params.get("purge_tags")
582
583 if not vpc_id:
584 if not name:
585 module.fail_json("The name parameter must be specified when creating a new VPC.")
586 vpc_obj = create_vpc_net(connection, module, cidr_block[0], tenancy, tags, ipv6_cidr, name)
587 vpc_id = vpc_obj["VpcId"]
588 changed = True
589 # Set on-creation defaults
590 if dns_hostnames is None:
591 dns_hostnames = True
592 if dns_support is None:
593 dns_support = True
594 else:
595 changed = False
596 vpc_obj = get_vpc(module, connection, vpc_id)
597 changed |= update_ipv6_cidrs(connection, module, vpc_obj, vpc_id, ipv6_cidr)
598 changed |= update_vpc_tags(connection, module, vpc_id, tags, name, purge_tags)
599
600 cidrs_changed, desired_cidrs = update_cidrs(connection, module, vpc_obj, cidr_block, purge_cidrs)
601 changed |= cidrs_changed
602 changed |= update_dhcp_opts(connection, module, vpc_obj, dhcp_id)
603 changed |= update_dns_enabled(connection, module, vpc_id, dns_support)
604 changed |= update_dns_hostnames(connection, module, vpc_id, dns_hostnames)
605
606 wait_for_updates(connection, module, vpc_id, ipv6_cidr, desired_cidrs, dns_support, dns_hostnames, tags, dhcp_id)
607
608 updated_obj = get_vpc(module, connection, vpc_id)
609 final_state = camel_dict_to_snake_dict(updated_obj)
610 final_state["tags"] = boto3_tag_list_to_ansible_dict(updated_obj.get("Tags", []))
611 final_state["name"] = final_state["tags"].get("Name", None)
612 final_state["id"] = final_state.pop("vpc_id")
613
614 module.exit_json(changed=changed, vpc=final_state)
615
616
617 def ensure_absent(connection, module: AnsibleAWSModule, vpc_id: str) -> None:
618 changed = False
619 if vpc_id:
620 if module.check_mode:
621 changed = True
622 else:
623 changed = delete_vpc(connection, vpc_id=vpc_id)
624 module.exit_json(changed=changed, vpc={})
625
626
627 def main():
628 argument_spec = dict(
629 name=dict(required=False),
630 vpc_id=dict(type="str", required=False, default=None),
631 cidr_block=dict(type="list", elements="str"),
632 ipv6_cidr=dict(type="bool", default=None),
633 tenancy=dict(choices=["default", "dedicated"], default="default"),
634 dns_support=dict(type="bool"),
635 dns_hostnames=dict(type="bool"),
636 dhcp_opts_id=dict(),
637 tags=dict(type="dict", aliases=["resource_tags"]),
638 purge_tags=dict(type="bool", default=True),
639 state=dict(choices=["present", "absent"], default="present"),
640 multi_ok=dict(type="bool", default=False),
641 purge_cidrs=dict(type="bool", default=False),
642 )
643 required_one_of = [
644 ["vpc_id", "name"],
645 ["vpc_id", "cidr_block"],
646 ]
647
648 module = AnsibleAWSModule(argument_spec=argument_spec, required_one_of=required_one_of, supports_check_mode=True)
649
650 dns_support = module.params.get("dns_support")
651 dns_hostnames = module.params.get("dns_hostnames")
652 state = module.params.get("state")
653
654 if dns_hostnames and not dns_support:
655 module.fail_json(msg="In order to enable DNS Hostnames you must also enable DNS support")
656
657 connection = module.client("ec2")
658 try:
659 vpc_id = module.params.get("vpc_id") or get_vpc_id(connection, module)
660 if state == "present":
661 ensure_present(connection, module, vpc_id)
662 else:
663 ensure_absent(connection, module, vpc_id)
664 except AnsibleEC2Error as e:
665 module.fail_json_aws_error(e)
666
667
668 if __name__ == "__main__":
669 main()