| 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_vpc_route_table |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Manage route tables for AWS Virtual Private Clouds |
| 12 |
description: |
| 13 |
- Manage route tables for AWS Virtual Private Clouds (VPCs). |
| 14 |
author: |
| 15 |
- Robert Estelle (@erydo) |
| 16 |
- Rob White (@wimnat) |
| 17 |
- Will Thames (@willthames) |
| 18 |
options: |
| 19 |
gateway_id: |
| 20 |
description: |
| 21 |
- The ID of the gateway to associate with the route table. |
| 22 |
- If O(gateway_id) is V('None') or V(''), gateway will be disassociated with the route table. |
| 23 |
type: str |
| 24 |
version_added: 3.2.0 |
| 25 |
lookup: |
| 26 |
description: |
| 27 |
- Look up route table by either O(tags) or by O(route_table_id). |
| 28 |
- If O(lookup=tag) and O(tags) is not specified then no lookup for an |
| 29 |
existing route table is performed and a new route table will be created. |
| 30 |
- When using O(lookup=tag), multiple matches being found will result in |
| 31 |
a failure and no changes will be made. |
| 32 |
- To change the tags of a route table use O(lookup=id). |
| 33 |
- O(vpc_id) must be specified when O(lookup=tag). |
| 34 |
default: tag |
| 35 |
choices: [ 'tag', 'id' ] |
| 36 |
type: str |
| 37 |
propagating_vgw_ids: |
| 38 |
description: Enable route propagation from virtual gateways specified by ID. |
| 39 |
type: list |
| 40 |
elements: str |
| 41 |
purge_routes: |
| 42 |
description: Purge existing routes that are not found in routes. |
| 43 |
type: bool |
| 44 |
default: True |
| 45 |
purge_subnets: |
| 46 |
description: |
| 47 |
- Purge existing subnets that are not found in subnets. |
| 48 |
- Ignored unless the subnets option is supplied. |
| 49 |
default: True |
| 50 |
type: bool |
| 51 |
route_table_id: |
| 52 |
description: |
| 53 |
- The ID of the route table to update or delete. |
| 54 |
- Required when O(lookup=id). |
| 55 |
type: str |
| 56 |
routes: |
| 57 |
description: |
| 58 |
- List of routes in the route table. |
| 59 |
- Routes are specified as dicts containing the keys V(dest) and one of V(gateway_id), |
| 60 |
V(instance_id), V(network_interface_id), V(transit_gateway_id), or V(vpc_peering_connection_id). |
| 61 |
- The value of V(dest) is used for the destination match. It may be a IPv4 CIDR block |
| 62 |
or a IPv6 CIDR block. |
| 63 |
- If V(gateway_id) is specified, you can refer to the VPC's IGW by using the value V(igw). |
| 64 |
- Routes are required for present states. |
| 65 |
type: list |
| 66 |
elements: dict |
| 67 |
default: [] |
| 68 |
state: |
| 69 |
description: Create or destroy the VPC route table. |
| 70 |
default: present |
| 71 |
choices: [ 'present', 'absent' ] |
| 72 |
type: str |
| 73 |
subnets: |
| 74 |
description: An array of subnets to add to this route table. Subnets may be specified |
| 75 |
by either subnet ID, Name tag, or by a CIDR such as '10.0.0.0/24' or 'fd00::/8'. |
| 76 |
type: list |
| 77 |
elements: str |
| 78 |
vpc_id: |
| 79 |
description: |
| 80 |
- VPC ID of the VPC in which to create the route table. |
| 81 |
- Required when O(state=present) or O(lookup=tag). |
| 82 |
type: str |
| 83 |
notes: |
| 84 |
- Tags are used to uniquely identify route tables within a VPC when the O(route_table_id) is not supplied. |
| 85 |
extends_documentation_fragment: |
| 86 |
- amazon.aws.common.modules |
| 87 |
- amazon.aws.region.modules |
| 88 |
- amazon.aws.tags |
| 89 |
- amazon.aws.boto3 |
| 90 |
""" |
| 91 |
|
| 92 |
EXAMPLES = r""" |
| 93 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 94 |
|
| 95 |
# Basic creation example: |
| 96 |
- name: Set up public subnet route table |
| 97 |
amazon.aws.ec2_vpc_route_table: |
| 98 |
vpc_id: vpc-1245678 |
| 99 |
region: us-west-1 |
| 100 |
tags: |
| 101 |
Name: Public |
| 102 |
subnets: |
| 103 |
- "{{ jumpbox_subnet.subnet.id }}" |
| 104 |
- "{{ frontend_subnet.subnet.id }}" |
| 105 |
- "{{ vpn_subnet.subnet_id }}" |
| 106 |
routes: |
| 107 |
- dest: 0.0.0.0/0 |
| 108 |
gateway_id: "{{ igw.gateway_id }}" |
| 109 |
- dest: ::/0 |
| 110 |
gateway_id: "{{ igw.gateway_id }}" |
| 111 |
- dest: 0.0.0.0/0 |
| 112 |
gateway_id: "{{ transit_gateway_id }}" |
| 113 |
register: public_route_table |
| 114 |
|
| 115 |
- name: Create VPC gateway |
| 116 |
amazon.aws.ec2_vpc_igw: |
| 117 |
vpc_id: vpc-1245678 |
| 118 |
register: vpc_igw |
| 119 |
|
| 120 |
- name: Create gateway route table |
| 121 |
amazon.aws.ec2_vpc_route_table: |
| 122 |
vpc_id: vpc-1245678 |
| 123 |
tags: |
| 124 |
Name: Gateway route table |
| 125 |
gateway_id: "{{ vpc_igw.gateway_id }}" |
| 126 |
register: gateway_route_table |
| 127 |
|
| 128 |
- name: Disassociate gateway from route table |
| 129 |
amazon.aws.ec2_vpc_route_table: |
| 130 |
vpc_id: vpc-1245678 |
| 131 |
tags: |
| 132 |
Name: Gateway route table |
| 133 |
gateway_id: None |
| 134 |
register: gateway_route_table |
| 135 |
|
| 136 |
- name: Set up NAT-protected route table |
| 137 |
amazon.aws.ec2_vpc_route_table: |
| 138 |
vpc_id: vpc-1245678 |
| 139 |
region: us-west-1 |
| 140 |
tags: |
| 141 |
Name: Internal |
| 142 |
subnets: |
| 143 |
- "{{ application_subnet.subnet.id }}" |
| 144 |
- 'Database Subnet' |
| 145 |
- '10.0.0.0/8' |
| 146 |
routes: |
| 147 |
- dest: 0.0.0.0/0 |
| 148 |
instance_id: "{{ nat.instance_id }}" |
| 149 |
register: nat_route_table |
| 150 |
|
| 151 |
- name: delete route table |
| 152 |
amazon.aws.ec2_vpc_route_table: |
| 153 |
vpc_id: vpc-1245678 |
| 154 |
region: us-west-1 |
| 155 |
route_table_id: "{{ route_table.id }}" |
| 156 |
lookup: id |
| 157 |
state: absent |
| 158 |
""" |
| 159 |
|
| 160 |
RETURN = r""" |
| 161 |
route_table: |
| 162 |
description: Route Table result. |
| 163 |
returned: always |
| 164 |
type: complex |
| 165 |
contains: |
| 166 |
associations: |
| 167 |
description: List of associations between the route table and one or more subnets or a gateway. |
| 168 |
returned: always |
| 169 |
type: complex |
| 170 |
contains: |
| 171 |
association_state: |
| 172 |
description: The state of the association. |
| 173 |
returned: always |
| 174 |
type: complex |
| 175 |
contains: |
| 176 |
state: |
| 177 |
description: The state of the association. |
| 178 |
returned: always |
| 179 |
type: str |
| 180 |
sample: associated |
| 181 |
state_message: |
| 182 |
description: Additional information about the state of the association. |
| 183 |
returned: when available |
| 184 |
type: str |
| 185 |
sample: 'Creating association' |
| 186 |
gateway_id: |
| 187 |
description: ID of the internet gateway or virtual private gateway. |
| 188 |
returned: when route table is a gateway route table |
| 189 |
type: str |
| 190 |
sample: igw-03312309 |
| 191 |
main: |
| 192 |
description: Whether this is the main route table. |
| 193 |
returned: always |
| 194 |
type: bool |
| 195 |
sample: false |
| 196 |
route_table_association_id: |
| 197 |
description: ID of association between route table and subnet. |
| 198 |
returned: always |
| 199 |
type: str |
| 200 |
sample: rtbassoc-ab47cfc3 |
| 201 |
route_table_id: |
| 202 |
description: ID of the route table. |
| 203 |
returned: always |
| 204 |
type: str |
| 205 |
sample: rtb-bf779ed7 |
| 206 |
subnet_id: |
| 207 |
description: ID of the subnet. |
| 208 |
returned: when route table is a subnet route table |
| 209 |
type: str |
| 210 |
sample: subnet-82055af9 |
| 211 |
id: |
| 212 |
description: ID of the route table (same as RV(route_table.route_table_id) for backwards compatibility). |
| 213 |
returned: always |
| 214 |
type: str |
| 215 |
sample: rtb-bf779ed7 |
| 216 |
owner_id: |
| 217 |
description: AWS account owning resource. |
| 218 |
type: str |
| 219 |
sample: 123456789012 |
| 220 |
propagating_vgws: |
| 221 |
description: List of Virtual Private Gateways propagating routes. |
| 222 |
returned: always |
| 223 |
type: list |
| 224 |
sample: [] |
| 225 |
route_table_id: |
| 226 |
description: ID of the route table. |
| 227 |
returned: always |
| 228 |
type: str |
| 229 |
sample: rtb-bf779ed7 |
| 230 |
routes: |
| 231 |
description: List of routes in the route table. |
| 232 |
returned: always |
| 233 |
type: complex |
| 234 |
contains: |
| 235 |
destination_cidr_block: |
| 236 |
description: IPv4 CIDR block of destination |
| 237 |
returned: always |
| 238 |
type: str |
| 239 |
sample: 10.228.228.0/22 |
| 240 |
destination_ipv6_cidr_block: |
| 241 |
description: IPv6 CIDR block of destination |
| 242 |
returned: when the route includes an IPv6 destination |
| 243 |
type: str |
| 244 |
sample: 2600:1f1c:1b3:8f00:8000::/65 |
| 245 |
gateway_id: |
| 246 |
description: ID of the gateway. |
| 247 |
returned: when gateway is local or internet gateway |
| 248 |
type: str |
| 249 |
sample: local |
| 250 |
instance_id: |
| 251 |
description: ID of a NAT instance. |
| 252 |
returned: when the route is via an EC2 instance |
| 253 |
type: str |
| 254 |
sample: i-abcd123456789 |
| 255 |
instance_owner_id: |
| 256 |
description: AWS account owning the NAT instance. |
| 257 |
returned: when the route is via an EC2 instance |
| 258 |
type: str |
| 259 |
sample: 123456789012 |
| 260 |
nat_gateway_id: |
| 261 |
description: ID of the NAT gateway. |
| 262 |
returned: when the route is via a NAT gateway |
| 263 |
type: str |
| 264 |
sample: local |
| 265 |
carrier_gateway_id: |
| 266 |
description: ID of the Carrier gateway. |
| 267 |
returned: when the route is via a Carrier gateway |
| 268 |
type: str |
| 269 |
sample: local |
| 270 |
version_added: 6.0.0 |
| 271 |
transit_gateway_id: |
| 272 |
description: ID of the Transit gateway. |
| 273 |
returned: when the route is via a Transit gateway |
| 274 |
type: str |
| 275 |
sample: tgw-123456789012 |
| 276 |
version_added: 9.0.0 |
| 277 |
origin: |
| 278 |
description: mechanism through which the route is in the table. |
| 279 |
returned: always |
| 280 |
type: str |
| 281 |
sample: CreateRouteTable |
| 282 |
state: |
| 283 |
description: state of the route. |
| 284 |
returned: always |
| 285 |
type: str |
| 286 |
sample: active |
| 287 |
tags: |
| 288 |
description: Tags applied to the route table. |
| 289 |
returned: always |
| 290 |
type: dict |
| 291 |
sample: |
| 292 |
Name: Public route table |
| 293 |
Public: 'true' |
| 294 |
vpc_id: |
| 295 |
description: ID for the VPC in which the route lives. |
| 296 |
returned: always |
| 297 |
type: str |
| 298 |
sample: vpc-6e2d2407 |
| 299 |
""" |
| 300 |
|
| 301 |
import re |
| 302 |
from ipaddress import ip_network |
| 303 |
from time import sleep |
| 304 |
from typing import Any |
| 305 |
from typing import Dict |
| 306 |
from typing import List |
| 307 |
from typing import Optional |
| 308 |
from typing import Tuple |
| 309 |
|
| 310 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 311 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 312 |
|
| 313 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error |
| 314 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import associate_route_table |
| 315 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_route |
| 316 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_route_table |
| 317 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_route |
| 318 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_route_table |
| 319 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_ec2_tags |
| 320 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_internet_gateways |
| 321 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_route_tables |
| 322 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_subnets |
| 323 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import disassociate_route_table |
| 324 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import enable_vgw_route_propagation |
| 325 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags |
| 326 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import replace_route |
| 327 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 328 |
from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list |
| 329 |
from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state |
| 330 |
|
| 331 |
|
| 332 |
def find_subnets( |
| 333 |
connection, module: AnsibleAWSModule, vpc_id: str, identified_subnets: Optional[List[str]] |
| 334 |
) -> List[Dict[str, Any]]: |
| 335 |
""" |
| 336 |
Finds a list of subnets, each identified either by a raw ID, a unique |
| 337 |
'Name' tag, or a CIDR such as 10.0.0.0/8. |
| 338 |
""" |
| 339 |
CIDR_RE = re.compile(r"^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$") |
| 340 |
SUBNET_RE = re.compile(r"^subnet-[A-z0-9]+$") |
| 341 |
|
| 342 |
subnet_ids = [] |
| 343 |
subnet_names = [] |
| 344 |
subnet_cidrs = [] |
| 345 |
for subnet in identified_subnets or []: |
| 346 |
if re.match(SUBNET_RE, subnet): |
| 347 |
subnet_ids.append(subnet) |
| 348 |
elif re.match(CIDR_RE, subnet): |
| 349 |
subnet_cidrs.append(subnet) |
| 350 |
else: |
| 351 |
subnet_names.append(subnet) |
| 352 |
|
| 353 |
subnets_by_id = [] |
| 354 |
if subnet_ids: |
| 355 |
filters = ansible_dict_to_boto3_filter_list({"vpc-id": vpc_id}) |
| 356 |
try: |
| 357 |
subnets_by_id = describe_subnets(connection, SubnetIds=subnet_ids, Filters=filters) |
| 358 |
except AnsibleEC2Error as e: |
| 359 |
module.fail_json_aws(e, msg=f"Couldn't find subnet with id {subnet_ids}") |
| 360 |
|
| 361 |
subnets_by_cidr = [] |
| 362 |
if subnet_cidrs: |
| 363 |
filters = ansible_dict_to_boto3_filter_list({"vpc-id": vpc_id, "cidr": subnet_cidrs}) |
| 364 |
try: |
| 365 |
subnets_by_cidr = describe_subnets(connection, Filters=filters) |
| 366 |
except AnsibleEC2Error as e: |
| 367 |
module.fail_json_aws(e, msg=f"Couldn't find subnet with cidr {subnet_cidrs}") |
| 368 |
|
| 369 |
subnets_by_name = [] |
| 370 |
if subnet_names: |
| 371 |
filters = ansible_dict_to_boto3_filter_list({"vpc-id": vpc_id, "tag:Name": subnet_names}) |
| 372 |
try: |
| 373 |
subnets_by_name = describe_subnets(connection, Filters=filters) |
| 374 |
except AnsibleEC2Error as e: |
| 375 |
module.fail_json_aws(e, msg=f"Couldn't find subnet with names {subnet_names}") |
| 376 |
|
| 377 |
for name in subnet_names: |
| 378 |
matching_count = len( |
| 379 |
[1 for s in subnets_by_name for t in s.get("Tags", []) if t["Key"] == "Name" and t["Value"] == name] |
| 380 |
) |
| 381 |
if matching_count == 0: |
| 382 |
module.fail_json(msg=f'Subnet named "{name}" does not exist') |
| 383 |
elif matching_count > 1: |
| 384 |
module.fail_json(msg=f'Multiple subnets named "{name}"') |
| 385 |
|
| 386 |
return subnets_by_id + subnets_by_cidr + subnets_by_name |
| 387 |
|
| 388 |
|
| 389 |
def find_igw(connection, module: AnsibleAWSModule, vpc_id: str) -> str: |
| 390 |
""" |
| 391 |
Finds the Internet gateway for the given VPC ID. |
| 392 |
""" |
| 393 |
filters = ansible_dict_to_boto3_filter_list({"attachment.vpc-id": vpc_id}) |
| 394 |
igw = describe_internet_gateways(connection, Filters=filters) |
| 395 |
|
| 396 |
if len(igw) == 0: |
| 397 |
module.fail_json(msg=f"No IGWs found for VPC {vpc_id}") |
| 398 |
elif len(igw) > 1: |
| 399 |
module.fail_json(msg=f"Multiple IGWs found for VPC {vpc_id}") |
| 400 |
return igw[0]["InternetGatewayId"] |
| 401 |
|
| 402 |
|
| 403 |
def tags_match(match_tags, candidate_tags): |
| 404 |
return all((k in candidate_tags and candidate_tags[k] == v for k, v in match_tags.items())) |
| 405 |
|
| 406 |
|
| 407 |
def get_route_table_by_id(connection, route_table_id: str) -> Optional[Dict[str, Any]]: |
| 408 |
route_table = None |
| 409 |
route_tables = describe_route_tables(connection, RouteTableIds=[route_table_id]) |
| 410 |
|
| 411 |
if route_tables: |
| 412 |
route_table = route_tables[0] |
| 413 |
|
| 414 |
return route_table |
| 415 |
|
| 416 |
|
| 417 |
def get_route_table_by_tags( |
| 418 |
connection, module: AnsibleAWSModule, vpc_id: str, tags: Dict[str, str] |
| 419 |
) -> Optional[Dict[str, Any]]: |
| 420 |
count = 0 |
| 421 |
route_table = None |
| 422 |
filters = ansible_dict_to_boto3_filter_list({"vpc-id": vpc_id}) |
| 423 |
route_tables = describe_route_tables(connection, Filters=filters) |
| 424 |
|
| 425 |
for table in route_tables: |
| 426 |
this_tags = describe_ec2_tags(connection, module, table["RouteTableId"]) |
| 427 |
if tags_match(tags, this_tags): |
| 428 |
route_table = table |
| 429 |
count += 1 |
| 430 |
|
| 431 |
if count > 1: |
| 432 |
module.fail_json(msg="Tags provided do not identify a unique route table") |
| 433 |
return route_table |
| 434 |
|
| 435 |
|
| 436 |
def route_spec_matches_route(route_spec, route): |
| 437 |
if route_spec.get("GatewayId") and "nat-" in route_spec["GatewayId"]: |
| 438 |
route_spec["NatGatewayId"] = route_spec.pop("GatewayId") |
| 439 |
if route_spec.get("GatewayId") and "vpce-" in route_spec["GatewayId"]: |
| 440 |
if route_spec.get("DestinationCidrBlock", "").startswith("pl-"): |
| 441 |
route_spec["DestinationPrefixListId"] = route_spec.pop("DestinationCidrBlock") |
| 442 |
|
| 443 |
return set(route_spec.items()).issubset(route.items()) |
| 444 |
|
| 445 |
|
| 446 |
def route_spec_matches_route_cidr(route_spec, route): |
| 447 |
if route_spec.get("DestinationCidrBlock") and route.get("DestinationCidrBlock"): |
| 448 |
return route_spec.get("DestinationCidrBlock") == route.get("DestinationCidrBlock") |
| 449 |
if route_spec.get("DestinationIpv6CidrBlock") and route.get("DestinationIpv6CidrBlock"): |
| 450 |
return route_spec.get("DestinationIpv6CidrBlock") == route.get("DestinationIpv6CidrBlock") |
| 451 |
return False |
| 452 |
|
| 453 |
|
| 454 |
def rename_key(d, old_key, new_key): |
| 455 |
d[new_key] = d.pop(old_key) |
| 456 |
|
| 457 |
|
| 458 |
def index_of_matching_route(route_spec, routes_to_match): |
| 459 |
for i, route in enumerate(routes_to_match): |
| 460 |
if route_spec_matches_route(route_spec, route): |
| 461 |
return "exact", i |
| 462 |
elif "Origin" in route and route["Origin"] != "EnableVgwRoutePropagation": # only replace created routes |
| 463 |
if route_spec_matches_route_cidr(route_spec, route): |
| 464 |
return "replace", i |
| 465 |
|
| 466 |
|
| 467 |
def ensure_routes( |
| 468 |
connection, |
| 469 |
module: AnsibleAWSModule, |
| 470 |
route_table: Dict[str, Any], |
| 471 |
route_specs: List[Dict[str, Any]], |
| 472 |
purge_routes: bool, |
| 473 |
) -> bool: |
| 474 |
routes_to_match = list(route_table["Routes"]) |
| 475 |
route_specs_to_create = [] |
| 476 |
route_specs_to_recreate = [] |
| 477 |
for route_spec in route_specs: |
| 478 |
match = index_of_matching_route(route_spec, routes_to_match) |
| 479 |
if match is None: |
| 480 |
if route_spec.get("DestinationCidrBlock") or route_spec.get("DestinationIpv6CidrBlock"): |
| 481 |
route_specs_to_create.append(route_spec) |
| 482 |
else: |
| 483 |
module.warn( |
| 484 |
f"Skipping creating {route_spec} because it has no destination cidr block. To add VPC endpoints to" |
| 485 |
" route tables use the ec2_vpc_endpoint module." |
| 486 |
) |
| 487 |
else: |
| 488 |
if match[0] == "replace": |
| 489 |
if route_spec.get("DestinationCidrBlock"): |
| 490 |
route_specs_to_recreate.append(route_spec) |
| 491 |
else: |
| 492 |
module.warn(f"Skipping recreating route {route_spec} because it has no destination cidr block.") |
| 493 |
del routes_to_match[match[1]] |
| 494 |
|
| 495 |
routes_to_delete = [] |
| 496 |
if purge_routes: |
| 497 |
for route in routes_to_match: |
| 498 |
if not route.get("DestinationCidrBlock"): |
| 499 |
module.warn( |
| 500 |
f"Skipping purging route {route} because it has no destination cidr block. To remove VPC endpoints" |
| 501 |
" from route tables use the ec2_vpc_endpoint module." |
| 502 |
) |
| 503 |
continue |
| 504 |
if route["Origin"] == "CreateRoute": |
| 505 |
routes_to_delete.append(route) |
| 506 |
|
| 507 |
if module.check_mode: |
| 508 |
return bool(routes_to_delete or route_specs_to_create or route_specs_to_recreate) |
| 509 |
|
| 510 |
changed = False |
| 511 |
# Delete routes |
| 512 |
for route in routes_to_delete: |
| 513 |
changed |= delete_route( |
| 514 |
connection, |
| 515 |
route_table_id=route_table["RouteTableId"], |
| 516 |
DestinationCidrBlock=route["DestinationCidrBlock"], |
| 517 |
) |
| 518 |
# Replace routes |
| 519 |
for route_spec in route_specs_to_recreate: |
| 520 |
replace_route(connection, route_table_id=route_table["RouteTableId"], **route_spec) |
| 521 |
changed = True |
| 522 |
# Create routes |
| 523 |
for route_spec in route_specs_to_create: |
| 524 |
create_route(connection, route_table_id=route_table["RouteTableId"], **route_spec) |
| 525 |
changed = True |
| 526 |
|
| 527 |
return changed |
| 528 |
|
| 529 |
|
| 530 |
def ensure_subnet_association( |
| 531 |
connection, module: AnsibleAWSModule, vpc_id: str, route_table_id: str, subnet_id: str |
| 532 |
) -> Tuple[bool, Optional[str]]: |
| 533 |
filters = ansible_dict_to_boto3_filter_list({"association.subnet-id": subnet_id, "vpc-id": vpc_id}) |
| 534 |
route_tables = describe_route_tables(connection, Filters=filters) |
| 535 |
|
| 536 |
association_id = None |
| 537 |
for route_table in route_tables: |
| 538 |
if route_table.get("RouteTableId"): |
| 539 |
for association in route_table["Associations"]: |
| 540 |
if association["Main"]: |
| 541 |
continue |
| 542 |
if association["SubnetId"] == subnet_id: |
| 543 |
if route_table["RouteTableId"] == route_table_id: |
| 544 |
return False, association["RouteTableAssociationId"] |
| 545 |
if not module.check_mode: |
| 546 |
disassociate_route_table(connection, association["RouteTableAssociationId"]) |
| 547 |
return True, association_id |
| 548 |
|
| 549 |
if not module.check_mode: |
| 550 |
association_id = associate_route_table(connection, route_table_id=route_table_id, SubnetId=subnet_id)[ |
| 551 |
"AssociationId" |
| 552 |
] |
| 553 |
return True, association_id |
| 554 |
|
| 555 |
|
| 556 |
def ensure_subnet_associations( |
| 557 |
connection, |
| 558 |
module: AnsibleAWSModule, |
| 559 |
route_table: Dict[str, Any], |
| 560 |
subnets: List[Dict[str, Any]], |
| 561 |
purge_subnets: bool, |
| 562 |
) -> bool: |
| 563 |
current_association_ids = [ |
| 564 |
association["RouteTableAssociationId"] |
| 565 |
for association in route_table["Associations"] |
| 566 |
if not association["Main"] and association.get("SubnetId") |
| 567 |
] |
| 568 |
new_association_ids = [] |
| 569 |
changed = False |
| 570 |
for subnet in subnets: |
| 571 |
result, association_id = ensure_subnet_association( |
| 572 |
connection=connection, |
| 573 |
module=module, |
| 574 |
vpc_id=route_table["VpcId"], |
| 575 |
route_table_id=route_table["RouteTableId"], |
| 576 |
subnet_id=subnet["SubnetId"], |
| 577 |
) |
| 578 |
changed |= result |
| 579 |
if changed and module.check_mode: |
| 580 |
return True |
| 581 |
new_association_ids.append(association_id) |
| 582 |
|
| 583 |
if purge_subnets: |
| 584 |
to_delete = [ |
| 585 |
association_id for association_id in current_association_ids if association_id not in new_association_ids |
| 586 |
] |
| 587 |
for association_id in to_delete: |
| 588 |
changed = True |
| 589 |
if not module.check_mode: |
| 590 |
disassociate_route_table(connection, association_id) |
| 591 |
|
| 592 |
return changed |
| 593 |
|
| 594 |
|
| 595 |
def disassociate_gateway(connection, module: AnsibleAWSModule, route_table: Dict[str, Any]) -> bool: |
| 596 |
# Delete all gateway associations that have state = associated |
| 597 |
# Subnet associations are handled in its method |
| 598 |
changed = False |
| 599 |
associations_to_delete = [ |
| 600 |
association["RouteTableAssociationId"] |
| 601 |
for association in route_table["Associations"] |
| 602 |
if not association["Main"] |
| 603 |
and association.get("GatewayId") |
| 604 |
and association["AssociationState"]["State"] in ["associated", "associating"] |
| 605 |
] |
| 606 |
for association_id in associations_to_delete: |
| 607 |
changed = True |
| 608 |
if not module.check_mode: |
| 609 |
disassociate_route_table(connection, association_id) |
| 610 |
|
| 611 |
return changed |
| 612 |
|
| 613 |
|
| 614 |
def associate_gateway(connection, module: AnsibleAWSModule, route_table: Dict[str, Any], gateway_id: str) -> bool: |
| 615 |
filters = ansible_dict_to_boto3_filter_list({"association.gateway-id": gateway_id, "vpc-id": route_table["VpcId"]}) |
| 616 |
route_tables = describe_route_tables(connection, Filters=filters) |
| 617 |
|
| 618 |
for table in route_tables: |
| 619 |
if table.get("RouteTableId"): |
| 620 |
for association in table.get("Associations"): |
| 621 |
if association["Main"]: |
| 622 |
continue |
| 623 |
if association.get("GatewayId", "") == gateway_id and ( |
| 624 |
association["AssociationState"]["State"] in ["associated", "associating"] |
| 625 |
): |
| 626 |
if table["RouteTableId"] == route_table["RouteTableId"]: |
| 627 |
return False |
| 628 |
elif module.check_mode: |
| 629 |
return True |
| 630 |
else: |
| 631 |
disassociate_route_table(connection, association["RouteTableAssociationId"]) |
| 632 |
|
| 633 |
if not module.check_mode: |
| 634 |
associate_route_table(connection, route_table_id=route_table["RouteTableId"], GatewayId=gateway_id) |
| 635 |
return True |
| 636 |
|
| 637 |
|
| 638 |
def ensure_propagation( |
| 639 |
connection, module: AnsibleAWSModule, route_table: Dict[str, Any], propagating_vgw_ids: List[str] |
| 640 |
) -> bool: |
| 641 |
changed = False |
| 642 |
gateways = [gateway["GatewayId"] for gateway in route_table["PropagatingVgws"]] |
| 643 |
vgws_to_add = set(propagating_vgw_ids) - set(gateways) |
| 644 |
if not vgws_to_add: |
| 645 |
return changed |
| 646 |
changed = True |
| 647 |
if module.check_mode: |
| 648 |
return changed |
| 649 |
for vgw_id in vgws_to_add: |
| 650 |
enable_vgw_route_propagation(connection, route_table_id=route_table["RouteTableId"], gateway_id=vgw_id) |
| 651 |
|
| 652 |
return changed |
| 653 |
|
| 654 |
|
| 655 |
def ensure_route_table_absent(connection, module: AnsibleAWSModule) -> Dict[str, bool]: |
| 656 |
lookup = module.params.get("lookup") |
| 657 |
route_table_id = module.params.get("route_table_id") |
| 658 |
tags = module.params.get("tags") |
| 659 |
vpc_id = module.params.get("vpc_id") |
| 660 |
purge_subnets = module.params.get("purge_subnets") |
| 661 |
route_table = None |
| 662 |
|
| 663 |
if lookup == "tag" and tags is not None: |
| 664 |
route_table = get_route_table_by_tags(connection, module, vpc_id, tags) |
| 665 |
elif lookup == "id": |
| 666 |
route_table = get_route_table_by_id(connection, route_table_id) |
| 667 |
|
| 668 |
if route_table is None: |
| 669 |
return {"changed": False} |
| 670 |
|
| 671 |
# disassociate subnets and gateway before deleting route table |
| 672 |
changed = False |
| 673 |
if module.check_mode: |
| 674 |
changed = True |
| 675 |
else: |
| 676 |
changed = ensure_subnet_associations( |
| 677 |
connection=connection, module=module, route_table=route_table, subnets=[], purge_subnets=purge_subnets |
| 678 |
) |
| 679 |
changed |= disassociate_gateway(connection=connection, module=module, route_table=route_table) |
| 680 |
changed |= delete_route_table(connection, route_table_id=route_table["RouteTableId"]) |
| 681 |
|
| 682 |
return {"changed": changed} |
| 683 |
|
| 684 |
|
| 685 |
def get_route_table_info(connection, module: AnsibleAWSModule, route_table: Dict[str, Any]) -> Optional[Dict[str, Any]]: |
| 686 |
result = get_route_table_by_id(connection, route_table["RouteTableId"]) or {} |
| 687 |
if result: |
| 688 |
result["Tags"] = describe_ec2_tags(connection, module, route_table["RouteTableId"]) |
| 689 |
result = camel_dict_to_snake_dict(result, ignore_list=["Tags"]) |
| 690 |
# backwards compatibility |
| 691 |
result["id"] = result["route_table_id"] |
| 692 |
return result |
| 693 |
|
| 694 |
|
| 695 |
def create_route_spec(connection, module, vpc_id): |
| 696 |
routes = module.params.get("routes") |
| 697 |
for route_spec in routes: |
| 698 |
cidr_block_type = str(type(ip_network(route_spec["dest"]))) |
| 699 |
if "IPv4" in cidr_block_type: |
| 700 |
rename_key(route_spec, "dest", "destination_cidr_block") |
| 701 |
if "IPv6" in cidr_block_type: |
| 702 |
rename_key(route_spec, "dest", "destination_ipv6_cidr_block") |
| 703 |
|
| 704 |
if route_spec.get("gateway_id") and route_spec["gateway_id"].lower() == "igw": |
| 705 |
igw = find_igw(connection, module, vpc_id) |
| 706 |
route_spec["gateway_id"] = igw |
| 707 |
if route_spec.get("gateway_id") and route_spec["gateway_id"].startswith("nat-"): |
| 708 |
rename_key(route_spec, "gateway_id", "nat_gateway_id") |
| 709 |
if route_spec.get("gateway_id") and route_spec["gateway_id"].startswith("cagw-"): |
| 710 |
rename_key(route_spec, "gateway_id", "carrier_gateway_id") |
| 711 |
if route_spec.get("gateway_id") and route_spec["gateway_id"].startswith("tgw-"): |
| 712 |
rename_key(route_spec, "gateway_id", "transit_gateway_id") |
| 713 |
|
| 714 |
return snake_dict_to_camel_dict(routes, capitalize_first=True) |
| 715 |
|
| 716 |
|
| 717 |
def ensure_route_table_present(connection, module: AnsibleAWSModule) -> Dict[str, Any]: |
| 718 |
gateway_id = module.params.get("gateway_id") |
| 719 |
lookup = module.params.get("lookup") |
| 720 |
propagating_vgw_ids = module.params.get("propagating_vgw_ids") |
| 721 |
purge_routes = module.params.get("purge_routes") |
| 722 |
purge_subnets = module.params.get("purge_subnets") |
| 723 |
purge_tags = module.params.get("purge_tags") |
| 724 |
route_table_id = module.params.get("route_table_id") |
| 725 |
subnets = module.params.get("subnets") |
| 726 |
tags = module.params.get("tags") |
| 727 |
vpc_id = module.params.get("vpc_id") |
| 728 |
routes = create_route_spec(connection, module, vpc_id) |
| 729 |
|
| 730 |
changed = False |
| 731 |
tags_valid = False |
| 732 |
route_table = None |
| 733 |
|
| 734 |
if lookup == "tag" and tags is not None: |
| 735 |
route_table = get_route_table_by_tags(connection, module, vpc_id, tags) |
| 736 |
elif lookup == "id": |
| 737 |
route_table = get_route_table_by_id(connection, route_table_id) |
| 738 |
|
| 739 |
# If no route table returned then create new route table |
| 740 |
if route_table is None: |
| 741 |
changed = True |
| 742 |
if module.check_mode: |
| 743 |
route_table = {"id": "rtb-xxxxxxxx", "route_table_id": "rtb-xxxxxxxx", "vpc_id": vpc_id} |
| 744 |
module.exit_json(changed=changed, route_table=route_table) |
| 745 |
|
| 746 |
route_table = create_route_table(connection, vpc_id, tags) |
| 747 |
# try to wait for route table to be present before moving on |
| 748 |
wait_for_resource_state(connection, module, "route_table_exists", RouteTableIds=[route_table["RouteTableId"]]) |
| 749 |
|
| 750 |
if routes is not None: |
| 751 |
changed |= ensure_routes( |
| 752 |
connection=connection, module=module, route_table=route_table, route_specs=routes, purge_routes=purge_routes |
| 753 |
) |
| 754 |
|
| 755 |
if propagating_vgw_ids is not None: |
| 756 |
changed |= ensure_propagation( |
| 757 |
connection=connection, module=module, route_table=route_table, propagating_vgw_ids=propagating_vgw_ids |
| 758 |
) |
| 759 |
|
| 760 |
if not tags_valid and tags is not None: |
| 761 |
changed |= ensure_ec2_tags( |
| 762 |
connection, |
| 763 |
module, |
| 764 |
route_table["RouteTableId"], |
| 765 |
tags=tags, |
| 766 |
purge_tags=purge_tags, |
| 767 |
retry_codes=["InvalidRouteTableID.NotFound"], |
| 768 |
) |
| 769 |
route_table["Tags"] = describe_ec2_tags(connection, module, route_table["RouteTableId"]) |
| 770 |
|
| 771 |
if subnets is not None: |
| 772 |
associated_subnets = find_subnets(connection, module, vpc_id, subnets) |
| 773 |
changed |= ensure_subnet_associations( |
| 774 |
connection=connection, |
| 775 |
module=module, |
| 776 |
route_table=route_table, |
| 777 |
subnets=associated_subnets, |
| 778 |
purge_subnets=purge_subnets, |
| 779 |
) |
| 780 |
|
| 781 |
if gateway_id == "None" or gateway_id == "": |
| 782 |
gateway_changed = disassociate_gateway(connection=connection, module=module, route_table=route_table) |
| 783 |
elif gateway_id is not None: |
| 784 |
gateway_changed = associate_gateway( |
| 785 |
connection=connection, module=module, route_table=route_table, gateway_id=gateway_id |
| 786 |
) |
| 787 |
else: |
| 788 |
gateway_changed = False |
| 789 |
changed = changed or gateway_changed |
| 790 |
|
| 791 |
if changed: |
| 792 |
# pause to allow route table routes/subnets/associations to be updated before exiting with final state |
| 793 |
sleep(5) |
| 794 |
|
| 795 |
return dict(changed=changed, route_table=get_route_table_info(connection, module, route_table)) |
| 796 |
|
| 797 |
|
| 798 |
def main() -> None: |
| 799 |
argument_spec = dict( |
| 800 |
gateway_id=dict(type="str"), |
| 801 |
lookup=dict(default="tag", choices=["tag", "id"]), |
| 802 |
propagating_vgw_ids=dict(type="list", elements="str"), |
| 803 |
purge_routes=dict(default=True, type="bool"), |
| 804 |
purge_subnets=dict(default=True, type="bool"), |
| 805 |
purge_tags=dict(type="bool", default=True), |
| 806 |
route_table_id=dict(), |
| 807 |
routes=dict(default=[], type="list", elements="dict"), |
| 808 |
state=dict(default="present", choices=["present", "absent"]), |
| 809 |
subnets=dict(type="list", elements="str"), |
| 810 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 811 |
vpc_id=dict(), |
| 812 |
) |
| 813 |
|
| 814 |
module = AnsibleAWSModule( |
| 815 |
argument_spec=argument_spec, |
| 816 |
required_if=[ |
| 817 |
["lookup", "id", ["route_table_id"]], |
| 818 |
["lookup", "tag", ["vpc_id"]], |
| 819 |
["state", "present", ["vpc_id"]], |
| 820 |
], |
| 821 |
supports_check_mode=True, |
| 822 |
) |
| 823 |
|
| 824 |
connection = module.client("ec2") |
| 825 |
method_operation = ( |
| 826 |
ensure_route_table_present if module.params.get("state") == "present" else ensure_route_table_absent |
| 827 |
) |
| 828 |
|
| 829 |
try: |
| 830 |
result = method_operation(connection, module) |
| 831 |
except AnsibleEC2Error as e: |
| 832 |
module.fail_json_aws_error(e) |
| 833 |
|
| 834 |
module.exit_json(**result) |
| 835 |
|
| 836 |
|
| 837 |
if __name__ == "__main__": |
| 838 |
main() |