Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_vpc_subnet.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_subnet
10 version_added: 1.0.0
11 short_description: Manage subnets in AWS virtual private clouds
12 description:
13 - Manage subnets in AWS virtual private clouds.
14 author:
15 - Robert Estelle (@erydo)
16 - Brad Davidson (@brandond)
17 options:
18 az:
19 description:
20 - The availability zone for the subnet.
21 - Required if O(outpost_arn) is set.
22 type: str
23 cidr:
24 description:
25 - The CIDR block for the subnet. E.g. V(192.0.2.0/24).
26 type: str
27 required: true
28 ipv6_cidr:
29 description:
30 - The IPv6 CIDR block for the subnet.
31 - The VPC must have a /56 block assigned and this value must be a valid IPv6 /64 that falls in the VPC range.
32 - Required if O(assign_instances_ipv6=true)
33 type: str
34 default: ''
35 outpost_arn:
36 description:
37 - The Amazon Resource Name (ARN) of the Outpost.
38 - If set, allows to create subnet in an Outpost.
39 - If O(outpost_arn) is set, O(az) must also be specified.
40 type: str
41 default: ''
42 state:
43 description:
44 - Create or remove the subnet.
45 default: present
46 choices: [ 'present', 'absent' ]
47 type: str
48 vpc_id:
49 description:
50 -"VPC ID of the VPC in which to create or delete the subnet.
51 required: true
52 type: str
53 map_public:
54 description:
55 - Whether instances launched into the subnet should default to being assigned public IP address.
56 type: bool
57 default: false
58 assign_instances_ipv6:
59 description:
60 - Whether instances launched into the subnet should default to being automatically assigned an IPv6 address.
61 - If O(assign_instances_ipv6=true), O(ipv6_cidr) must also be specified.
62 type: bool
63 default: false
64 wait:
65 description:
66 - Whether to wait for changes to complete.
67 type: bool
68 default: true
69 wait_timeout:
70 description:
71 - Number of seconds to wait for changes to complete
72 - Ignored unless O(wait=true).
73 default: 300
74 type: int
75 extends_documentation_fragment:
76 - amazon.aws.common.modules
77 - amazon.aws.region.modules
78 - amazon.aws.tags
79 - amazon.aws.boto3
80 """
81
82 EXAMPLES = r"""
83 # Note: These examples do not set authentication details, see the AWS Guide for details.
84
85 - name: Create subnet for database servers
86 amazon.aws.ec2_vpc_subnet:
87 state: present
88 vpc_id: vpc-123456
89 cidr: 10.0.1.16/28
90 tags:
91 Name: Database Subnet
92 register: database_subnet
93
94 - name: Remove subnet for database servers
95 amazon.aws.ec2_vpc_subnet:
96 state: absent
97 vpc_id: vpc-123456
98 cidr: 10.0.1.16/28
99
100 - name: Create subnet with IPv6 block assigned
101 amazon.aws.ec2_vpc_subnet:
102 state: present
103 vpc_id: vpc-123456
104 cidr: 10.1.100.0/24
105 ipv6_cidr: 2001:db8:0:102::/64
106
107 - name: Remove IPv6 block assigned to subnet
108 amazon.aws.ec2_vpc_subnet:
109 state: present
110 vpc_id: vpc-123456
111 cidr: 10.1.100.0/24
112 ipv6_cidr: ''
113 """
114
115 RETURN = r"""
116 subnet:
117 description: Dictionary of subnet values.
118 returned: O(state=present)
119 type: complex
120 contains:
121 id:
122 description: Subnet resource id.
123 returned: O(state=present)
124 type: str
125 sample: subnet-b883b2c4
126 cidr_block:
127 description: The IPv4 CIDR of the Subnet.
128 returned: O(state=present)
129 type: str
130 sample: "10.0.0.0/16"
131 ipv6_cidr_block:
132 description: The IPv6 CIDR block actively associated with the Subnet.
133 returned: O(state=present)
134 type: str
135 sample: "2001:db8:0:102::/64"
136 availability_zone:
137 description: Availability zone of the Subnet.
138 returned: O(state=present)
139 type: str
140 sample: us-east-1a
141 availability_zone_id:
142 description: The AZ ID of the subnet.
143 returned: O(state=present)
144 type: str
145 sample: use1-az6
146 state:
147 description: State of the Subnet.
148 returned: O(state=present)
149 type: str
150 sample: available
151 tags:
152 description: Tags attached to the Subnet, includes name.
153 returned: O(state=present)
154 type: dict
155 sample: {"Name": "My Subnet", "env": "staging"}
156 map_public_ip_on_launch:
157 description: Whether public IP is auto-assigned to new instances.
158 returned: O(state=present)
159 type: bool
160 sample: false
161 assign_ipv6_address_on_creation:
162 description: Whether IPv6 address is auto-assigned to new instances.
163 returned: O(state=present)
164 type: bool
165 sample: false
166 vpc_id:
167 description: The id of the VPC where this Subnet exists.
168 returned: O(state=present)
169 type: str
170 sample: vpc-67236184
171 available_ip_address_count:
172 description: Number of available IPv4 addresses.
173 returned: O(state=present)
174 type: str
175 sample: 251
176 default_for_az:
177 description: Indicates whether this is the default Subnet for this Availability Zone.
178 returned: O(state=present)
179 type: bool
180 sample: false
181 enable_dns64:
182 description:
183 - Indicates whether DNS queries made should return synthetic IPv6 addresses for IPv4-only destinations.
184 type: bool
185 sample: false
186 ipv6_association_id:
187 description: The IPv6 association ID for the currently associated CIDR.
188 returned: O(state=present)
189 type: str
190 sample: subnet-cidr-assoc-b85c74d2
191 ipv6_native:
192 description: Indicates whether this is an IPv6 only subnet.
193 type: bool
194 sample: false
195 ipv6_cidr_block_association_set:
196 description: An array of IPv6 cidr block association set information.
197 returned: O(state=present)
198 type: complex
199 contains:
200 association_id:
201 description: The association ID.
202 returned: always
203 type: str
204 ipv6_cidr_block:
205 description: The IPv6 CIDR block that is associated with the subnet.
206 returned: always
207 type: str
208 ipv6_cidr_block_state:
209 description: A hash/dict that contains a single item. The state of the cidr block association.
210 returned: always
211 type: dict
212 contains:
213 state:
214 description: The CIDR block association state.
215 returned: always
216 type: str
217 map_customer_owned_ip_on_launch:
218 description:
219 - Indicates whether a network interface receives a customer-owned IPv4 address.
220 type: bool
221 sample: flase
222 owner_id:
223 description: The ID of the Amazon Web Services account that owns the subnet.
224 type: str
225 sample: 12344567
226 private_dns_name_options_on_launch:
227 description:
228 - The type of hostnames to assign to instances in the subnet at launch.
229 - An instance hostname is based on the IPv4 address or ID of the instance.
230 type: dict
231 sample: {
232 "enable_resource_name_dns_a_record": false,
233 "enable_resource_name_dns_aaaa_record": false,
234 "hostname_type": "ip-name"
235 }
236 subnet_arn:
237 description: The Amazon Resource Name (ARN) of the subnet.
238 type: str
239 sample: arn:aws:ec2:us-east-1:xxx:subnet/subnet-xxx
240
241 """
242
243
244 import time
245 from typing import Any
246 from typing import Dict
247 from typing import List
248 from typing import Optional
249 from typing import Tuple
250 from typing import Union
251
252 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
253
254 from ansible_collections.amazon.aws.plugins.module_utils.arn import is_outpost_arn
255 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
256 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import associate_subnet_cidr_block
257 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_subnet
258 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_subnet
259 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_subnets
260 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import disassociate_subnet_cidr_block
261 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
262 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_subnet_attribute
263 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
264 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_tag_filter_dict
265 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
266 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
267 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
268 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
269
270
271 def get_subnet_info(subnet: Dict[str, Any]) -> Dict[str, Any]:
272 subnet = camel_dict_to_snake_dict(subnet)
273 if "tags" in subnet:
274 subnet["tags"] = boto3_tag_list_to_ansible_dict(subnet["tags"])
275 else:
276 subnet["tags"] = dict()
277
278 if "subnet_id" in subnet:
279 subnet["id"] = subnet["subnet_id"]
280 del subnet["subnet_id"]
281
282 subnet["ipv6_cidr_block"] = ""
283 subnet["ipv6_association_id"] = ""
284 ipv6set = subnet.get("ipv6_cidr_block_association_set")
285 if ipv6set:
286 for item in ipv6set:
287 if item.get("ipv6_cidr_block_state", {}).get("state") in ("associated", "associating"):
288 subnet["ipv6_cidr_block"] = item["ipv6_cidr_block"]
289 subnet["ipv6_association_id"] = item["association_id"]
290
291 return subnet
292
293
294 def wait_vpc_subnet_state(conn, module: AnsibleAWSModule, waiter_name: str, start_time: float, **params) -> None:
295 max_attempts = int(module.params["wait_timeout"] + start_time - time.time())
296 wait_for_resource_state(conn, module, waiter_name, delay=5, max_attempts=max_attempts, **params)
297
298
299 def create_vpc_subnet(
300 connection,
301 module: AnsibleAWSModule,
302 start_time: float,
303 ) -> Dict[str, Any]:
304 vpc_id = module.params["vpc_id"]
305 cidr = module.params["cidr"]
306 tags = module.params["tags"]
307 ipv6_cidr = module.params["ipv6_cidr"]
308 outpost_arn = module.params["outpost_arn"]
309 az = module.params["az"]
310 wait = module.params["wait"]
311
312 params = {"VpcId": vpc_id, "CidrBlock": cidr}
313
314 if ipv6_cidr:
315 params["Ipv6CidrBlock"] = ipv6_cidr
316 if az:
317 params["AvailabilityZone"] = az
318 if tags:
319 params["TagSpecifications"] = boto3_tag_specifications(tags, types="subnet")
320 if outpost_arn:
321 if is_outpost_arn(outpost_arn):
322 params["OutpostArn"] = outpost_arn
323 else:
324 module.fail_json("OutpostArn does not match the pattern specified in API specifications.")
325
326 try:
327 subnet = get_subnet_info(create_subnet(connection, **params))
328 except AnsibleEC2Error as e:
329 module.fail_json_aws_error(e)
330
331 # Sometimes AWS takes its time to create a subnet and so using
332 # new subnets's id to do things like create tags results in
333 # exception.
334 if wait and subnet.get("state") != "available":
335 wait_vpc_subnet_state(connection, module, "subnet_exists", start_time=start_time, SubnetIds=[subnet["id"]])
336 wait_vpc_subnet_state(connection, module, "subnet_available", start_time=start_time, SubnetIds=[subnet["id"]])
337 subnet["state"] = "available"
338
339 return subnet
340
341
342 def disassociate_ipv6_cidr(conn, module: AnsibleAWSModule, subnet: Dict[str, Any], start_time: float):
343 if subnet.get("assign_ipv6_address_on_creation"):
344 try:
345 modify_subnet_attribute(conn, subnet["id"], AssignIpv6AddressOnCreation={"Value": False})
346 except AnsibleEC2Error as e:
347 module.fail_json_aws_error(e)
348
349 try:
350 disassociate_subnet_cidr_block(conn, subnet["ipv6_association_id"])
351 except AnsibleEC2Error as e:
352 module.fail_json_aws(
353 e,
354 msg=f"Couldn't disassociate ipv6 cidr block id {subnet['ipv6_association_id']} from subnet {subnet['id']}",
355 )
356
357 # Wait for cidr block to be disassociated
358 if module.params["wait"]:
359 filters = ansible_dict_to_boto3_filter_list(
360 {"ipv6-cidr-block-association.state": ["disassociated"], "vpc-id": subnet["vpc_id"]}
361 )
362 wait_vpc_subnet_state(
363 conn, module, "subnet_exists", start_time=start_time, SubnetIds=[subnet["id"]], Filters=filters
364 )
365
366
367 def ensure_ipv6_cidr_block(conn, module: AnsibleAWSModule, subnet: Dict[str, Any], start_time: float) -> bool:
368 ipv6_cidr = module.params["ipv6_cidr"]
369 wait = module.params["wait"]
370 changed = False
371
372 if subnet["ipv6_association_id"] and not ipv6_cidr:
373 if not module.check_mode:
374 disassociate_ipv6_cidr(conn, module, subnet, start_time)
375 changed = True
376
377 if ipv6_cidr:
378 filters = ansible_dict_to_boto3_filter_list(
379 {"ipv6-cidr-block-association.ipv6-cidr-block": ipv6_cidr, "vpc-id": subnet["vpc_id"]}
380 )
381
382 try:
383 check_subnets = [get_subnet_info(x) for x in describe_subnets(client=conn, Filters=filters)]
384 except AnsibleEC2Error as e:
385 module.fail_json_aws_error(e)
386
387 if check_subnets and check_subnets[0]["ipv6_cidr_block"]:
388 module.fail_json(msg=f"The IPv6 CIDR '{ipv6_cidr}' conflicts with another subnet")
389
390 if subnet["ipv6_association_id"]:
391 if not module.check_mode:
392 disassociate_ipv6_cidr(conn, module, subnet, start_time)
393 changed = True
394
395 try:
396 if not module.check_mode:
397 associate_resp = associate_subnet_cidr_block(conn, subnet_id=subnet["id"], Ipv6CidrBlock=ipv6_cidr)
398 changed = True
399 except AnsibleEC2Error as e:
400 module.fail_json_aws(e, msg=f"Couldn't associate ipv6 cidr {ipv6_cidr} to {subnet['id']}")
401 else:
402 if not module.check_mode and wait:
403 filters = ansible_dict_to_boto3_filter_list(
404 {"ipv6-cidr-block-association.state": ["associated"], "vpc-id": subnet["vpc_id"]}
405 )
406 wait_vpc_subnet_state(
407 conn, module, "subnet_exists", start_time=start_time, SubnetIds=[subnet["id"]], Filters=filters
408 )
409 if not module.check_mode:
410 if associate_resp.get("AssociationId"):
411 subnet["ipv6_association_id"] = associate_resp["AssociationId"]
412 subnet["ipv6_cidr_block"] = associate_resp["Ipv6CidrBlock"]
413 if subnet["ipv6_cidr_block_association_set"]:
414 subnet["ipv6_cidr_block_association_set"][0] = camel_dict_to_snake_dict(associate_resp)
415 else:
416 subnet["ipv6_cidr_block_association_set"].append(camel_dict_to_snake_dict(associate_resp))
417
418 return changed
419
420
421 def _matching_subnet_filters(vpc_id: str, cidr: List[str]) -> Dict[str, Union[str, List[str]]]:
422 return ansible_dict_to_boto3_filter_list({"vpc-id": vpc_id, "cidr-block": cidr})
423
424
425 def get_matching_subnet(conn, module: AnsibleAWSModule, vpc_id: str, cidr: List[str]) -> Optional[Dict[str, Any]]:
426 filters = _matching_subnet_filters(vpc_id, cidr)
427 try:
428 for subnet in describe_subnets(client=conn, Filters=filters):
429 # The list contains only one subnet
430 return get_subnet_info(subnet)
431 except AnsibleEC2Error as e:
432 module.fail_json_aws_error(e)
433 return None
434
435
436 def update_subnet_attributes(
437 conn, module: AnsibleAWSModule, subnet: Dict[str, Any], start_time: float
438 ) -> Tuple[bool, Dict[str, Any]]:
439 changed = False
440 # Ensure IPv6 CIDR Block
441 if module.params["ipv6_cidr"] != subnet.get("ipv6_cidr_block"):
442 changed |= ensure_ipv6_cidr_block(conn, module, subnet, start_time)
443
444 # Modify subnet attribute 'MapPublicIpOnLaunch'
445 map_public = module.params["map_public"]
446 if map_public != subnet.get("map_public_ip_on_launch"):
447 changed = True
448 if not module.check_mode:
449 params = {"MapPublicIpOnLaunch": {"Value": map_public}}
450 modify_subnet_attribute(conn, subnet["id"], **params)
451
452 # Modify subnet attribute 'AssignIpv6AddressOnCreation'
453 assign_instances_ipv6 = module.params["assign_instances_ipv6"]
454 if assign_instances_ipv6 != subnet.get("assign_ipv6_address_on_creation"):
455 changed = True
456 if not module.check_mode:
457 params = {"AssignIpv6AddressOnCreation": {"Value": assign_instances_ipv6}}
458 modify_subnet_attribute(conn, subnet["id"], **params)
459
460 # Ensure subnet tags
461 tags_updated = ensure_ec2_tags(
462 conn,
463 module,
464 subnet["id"],
465 resource_type="subnet",
466 purge_tags=module.params["purge_tags"],
467 tags=module.params["tags"],
468 retry_codes=["InvalidSubnetID.NotFound"],
469 )
470 if tags_updated:
471 changed = True
472 if module.params["wait"] and not module.check_mode:
473 # Wait for tags to be updated
474 filters = ansible_dict_to_boto3_filter_list(ansible_dict_to_tag_filter_dict(module.params["tags"]))
475 wait_vpc_subnet_state(
476 conn, module, "subnet_exists", start_time=start_time, SubnetIds=[subnet["id"]], Filters=filters
477 )
478
479 subnet = get_matching_subnet(conn, module, module.params["vpc_id"], module.params["cidr"])
480 if not module.check_mode and module.params["wait"]:
481 subnet_filter = _matching_subnet_filters(module.params["vpc_id"], module.params["cidr"])
482 wait_vpc_subnet_state(
483 conn, module, "subnet_exists", start_time=start_time, SubnetIds=[subnet["id"]], Filters=subnet_filter
484 )
485 subnet = get_matching_subnet(conn, module, module.params["vpc_id"], module.params["cidr"])
486 if not subnet:
487 module.fail_json("Failed to describe newly created subnet")
488 # GET calls are not monotonic for map_public_ip_on_launch and assign_ipv6_address_on_creation
489 # so we only wait for those if necessary just before returning the subnet
490 subnet = ensure_final_subnet(conn, module, subnet, start_time)
491 return changed, subnet
492
493
494 def ensure_subnet_present(conn, module: AnsibleAWSModule) -> Dict[str, Any]:
495 subnet = get_matching_subnet(conn, module, module.params["vpc_id"], module.params["cidr"])
496 changed = False
497
498 # Initialize start so max time does not exceed the specified wait_timeout for multiple operations
499 start_time = time.time()
500
501 if subnet is None:
502 if not module.check_mode:
503 subnet = create_vpc_subnet(conn, module, start_time)
504 changed = True
505 # Subnet will be None when check_mode is true
506 if subnet is None:
507 return {"changed": changed, "subnet": {}}
508
509 attribute_change, subnet = update_subnet_attributes(conn, module, subnet, start_time)
510 return {"changed": changed or attribute_change, "subnet": subnet}
511
512
513 def ensure_final_subnet(conn, module: AnsibleAWSModule, subnet: Dict[str, Any], start_time: float) -> Dict[str, Any]:
514 for _rewait in range(0, 30):
515 map_public_correct = True
516 assign_ipv6_correct = True
517
518 if module.params["map_public"] != subnet["map_public_ip_on_launch"]:
519 map_public_correct = False
520 waiter_name = "subnet_has_map_public" if module.params["map_public"] else "subnet_no_map_public"
521 wait_vpc_subnet_state(conn, module, waiter_name, start_time=start_time, SubnetIds=[subnet["id"]])
522
523 if module.params["assign_instances_ipv6"] != subnet.get("assign_ipv6_address_on_creation"):
524 assign_ipv6_correct = False
525 waiter_name = (
526 "subnet_has_assign_ipv6" if module.params["assign_instances_ipv6"] else "subnet_no_assign_ipv6"
527 )
528 wait_vpc_subnet_state(conn, module, waiter_name, start_time=start_time, SubnetIds=[subnet["id"]])
529
530 if map_public_correct and assign_ipv6_correct:
531 break
532
533 time.sleep(5)
534 subnet = get_matching_subnet(conn, module, module.params["vpc_id"], module.params["cidr"]) or {}
535
536 return subnet
537
538
539 def ensure_subnet_absent(conn, module: AnsibleAWSModule) -> Dict[str, Any]:
540 subnet = get_matching_subnet(conn, module, module.params["vpc_id"], module.params["cidr"])
541 if subnet is None:
542 return {"changed": False}
543
544 try:
545 changed = False
546 if module.check_mode:
547 changed = True
548 else:
549 changed = delete_subnet(conn, subnet["id"])
550 if module.params["wait"]:
551 wait_vpc_subnet_state(conn, module, "subnet_deleted", start_time=time.time(), SubnetIds=[subnet["id"]])
552 except AnsibleEC2Error as e:
553 module.fail_json_aws_error(e)
554 return {"changed": changed}
555
556
557 def main() -> None:
558 argument_spec = dict(
559 az=dict(default=None, required=False),
560 cidr=dict(required=True),
561 ipv6_cidr=dict(default="", required=False),
562 outpost_arn=dict(default="", type="str", required=False),
563 state=dict(default="present", choices=["present", "absent"]),
564 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
565 vpc_id=dict(required=True),
566 map_public=dict(default=False, required=False, type="bool"),
567 assign_instances_ipv6=dict(default=False, required=False, type="bool"),
568 wait=dict(type="bool", default=True),
569 wait_timeout=dict(type="int", default=300, required=False),
570 purge_tags=dict(default=True, type="bool"),
571 )
572
573 required_if = [("assign_instances_ipv6", True, ["ipv6_cidr"])]
574
575 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True, required_if=required_if)
576
577 if module.params.get("outpost_arn") and not module.params.get("az"):
578 module.fail_json(msg="To specify OutpostArn, you must specify the Availability Zone of the Outpost subnet.")
579
580 if module.params.get("assign_instances_ipv6") and not module.params.get("ipv6_cidr"):
581 module.fail_json(msg="assign_instances_ipv6 is True but ipv6_cidr is None or an empty string")
582
583 connection = module.client("ec2")
584
585 state = module.params.get("state")
586
587 try:
588 if state == "present":
589 result = ensure_subnet_present(connection, module)
590 elif state == "absent":
591 result = ensure_subnet_absent(connection, module)
592 except AnsibleEC2Error as e:
593 module.fail_json_aws(e)
594
595 module.exit_json(**result)
596
597
598 if __name__ == "__main__":
599 main()