| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright (c) 2017 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_vpn |
| 10 |
version_added: 1.0.0 |
| 11 |
version_added_collection: community.aws |
| 12 |
short_description: Create, modify, and delete EC2 VPN connections |
| 13 |
description: |
| 14 |
- This module creates, modifies, and deletes VPN connections. |
| 15 |
- Idempotence is achieved by using the O(filters) option or specifying the VPN connection identifier. |
| 16 |
author: |
| 17 |
- Sloane Hertel (@s-hertel) |
| 18 |
options: |
| 19 |
state: |
| 20 |
description: |
| 21 |
- The desired state of the VPN connection. |
| 22 |
choices: ["present", "absent"] |
| 23 |
default: present |
| 24 |
required: false |
| 25 |
type: str |
| 26 |
customer_gateway_id: |
| 27 |
description: |
| 28 |
- The ID of the customer gateway. |
| 29 |
type: str |
| 30 |
connection_type: |
| 31 |
description: |
| 32 |
- The type of VPN connection. |
| 33 |
- At this time only V(ipsec.1) is supported. |
| 34 |
default: "ipsec.1" |
| 35 |
type: str |
| 36 |
vpn_gateway_id: |
| 37 |
description: |
| 38 |
- The ID of the virtual private gateway. |
| 39 |
- Mutually exclusive with O(transit_gateway_id). |
| 40 |
type: str |
| 41 |
vpn_connection_id: |
| 42 |
description: |
| 43 |
- The ID of the VPN connection. Required to modify or delete a connection if the filters option does not provide a unique match. |
| 44 |
type: str |
| 45 |
static_only: |
| 46 |
description: |
| 47 |
- Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP. |
| 48 |
default: false |
| 49 |
type: bool |
| 50 |
required: false |
| 51 |
transit_gateway_id: |
| 52 |
description: |
| 53 |
- The ID of the transit gateway. |
| 54 |
- Mutually exclusive with O(vpn_gateway_id). |
| 55 |
type: str |
| 56 |
version_added: 6.2.0 |
| 57 |
local_ipv4_network_cidr: |
| 58 |
description: |
| 59 |
- The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. |
| 60 |
required: false |
| 61 |
type: str |
| 62 |
default: "0.0.0.0/0" |
| 63 |
version_added: 9.0.0 |
| 64 |
tunnel_options: |
| 65 |
description: |
| 66 |
- An optional list object containing no more than two dict members, each of which may contain O(tunnel_options.TunnelInsideCidr) |
| 67 |
and/or O(tunnel_options.PreSharedKey) keys with appropriate string values. |
| 68 |
AWS defaults will apply in absence of either of the aforementioned keys. |
| 69 |
required: false |
| 70 |
type: list |
| 71 |
elements: dict |
| 72 |
default: [] |
| 73 |
suboptions: |
| 74 |
TunnelInsideCidr: |
| 75 |
type: str |
| 76 |
description: |
| 77 |
- The range of inside IPv4 addresses for the tunnel. |
| 78 |
TunnelInsideIpv6Cidr: |
| 79 |
type: str |
| 80 |
description: |
| 81 |
- The range of inside IPv6 addresses for the tunnel. |
| 82 |
version_added: 9.0.0 |
| 83 |
PreSharedKey: |
| 84 |
type: str |
| 85 |
description: |
| 86 |
- The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and customer gateway. |
| 87 |
filters: |
| 88 |
description: |
| 89 |
- An alternative to using O(vpn_connection_id). If multiple matches are found, O(vpn_connection_id) is required. |
| 90 |
If one of the following suboptions is a list of items to filter by, only one item needs to match to find the VPN |
| 91 |
that correlates. e.g. if the filter O(filters.cidr) is V(["194.168.2.0/24", "192.168.2.0/24"]) and the VPN route only has the |
| 92 |
destination cidr block of V(192.168.2.0/24) it will be found with this filter (assuming there are not multiple |
| 93 |
VPNs that are matched). Another example, if the filter O(filters.vpn) is equal to V(["vpn-ccf7e7ad", "vpn-cb0ae2a2"]) and one |
| 94 |
of of the VPNs has the state deleted (exists but is unmodifiable) and the other exists and is not deleted, |
| 95 |
it will be found via this filter. |
| 96 |
suboptions: |
| 97 |
cgw-config: |
| 98 |
description: |
| 99 |
- The customer gateway configuration of the VPN as a string (in the format of the return value) or a list of those strings. |
| 100 |
static-routes-only: |
| 101 |
description: |
| 102 |
- The type of routing; V(true) or V(false). |
| 103 |
type: bool |
| 104 |
cidr: |
| 105 |
description: |
| 106 |
- The destination cidr of the VPN's route as a string or a list of those strings. |
| 107 |
bgp: |
| 108 |
description: |
| 109 |
- The BGP ASN number associated with a BGP device. Only works if the connection is attached. |
| 110 |
This filtering option is currently not working. |
| 111 |
vpn: |
| 112 |
description: |
| 113 |
- The VPN connection id as a string or a list of those strings. |
| 114 |
vgw: |
| 115 |
description: |
| 116 |
- The virtual private gateway as a string or a list of those strings. |
| 117 |
tag-keys: |
| 118 |
description: |
| 119 |
- The key of a tag as a string or a list of those strings. |
| 120 |
tag-values: |
| 121 |
description: |
| 122 |
- The value of a tag as a string or a list of those strings. |
| 123 |
tags: |
| 124 |
description: |
| 125 |
- A dict of key value pairs. |
| 126 |
type: dict |
| 127 |
cgw: |
| 128 |
description: |
| 129 |
- The customer gateway id as a string or a list of those strings. |
| 130 |
type: dict |
| 131 |
default: {} |
| 132 |
routes: |
| 133 |
description: |
| 134 |
- Routes to add to the connection. |
| 135 |
type: list |
| 136 |
elements: str |
| 137 |
default: [] |
| 138 |
purge_routes: |
| 139 |
description: |
| 140 |
- Whether or not to delete VPN connections routes that are not specified in the task. |
| 141 |
type: bool |
| 142 |
default: false |
| 143 |
wait_timeout: |
| 144 |
description: |
| 145 |
- How long, in seconds, before wait gives up. |
| 146 |
default: 600 |
| 147 |
type: int |
| 148 |
required: false |
| 149 |
delay: |
| 150 |
description: |
| 151 |
- The time, in seconds, to wait before checking operation again. |
| 152 |
required: false |
| 153 |
type: int |
| 154 |
default: 15 |
| 155 |
extends_documentation_fragment: |
| 156 |
- amazon.aws.region.modules |
| 157 |
- amazon.aws.common.modules |
| 158 |
- amazon.aws.tags |
| 159 |
- amazon.aws.boto3 |
| 160 |
""" |
| 161 |
|
| 162 |
EXAMPLES = r""" |
| 163 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 164 |
|
| 165 |
- name: Create a VPN connection with vpn_gateway_id |
| 166 |
amazon.aws.ec2_vpc_vpn: |
| 167 |
state: "present" |
| 168 |
vpn_gateway_id: "vgw-XXXXXXXX" |
| 169 |
customer_gateway_id: "cgw-XXXXXXXX" |
| 170 |
|
| 171 |
- name: Attach a vpn connection to transit gateway |
| 172 |
amazon.aws.ec2_vpc_vpn: |
| 173 |
state: "present" |
| 174 |
transit_gateway_id: "tgw-XXXXXXXX" |
| 175 |
customer_gateway_id: "cgw-XXXXXXXX" |
| 176 |
|
| 177 |
- name: Modify VPN connection tags |
| 178 |
amazon.aws.ec2_vpc_vpn: |
| 179 |
state: "present" |
| 180 |
vpn_connection_id: "vpn-XXXXXXXX" |
| 181 |
tags: |
| 182 |
Name: "ansible-tag-1" |
| 183 |
Other: "ansible-tag-2" |
| 184 |
|
| 185 |
- name: Delete a connection |
| 186 |
amazon.aws.ec2_vpc_vpn: |
| 187 |
vpn_connection_id: "vpn-XXXXXXXX" |
| 188 |
state: "absent" |
| 189 |
|
| 190 |
- name: Modify VPN tags (identifying VPN by filters) |
| 191 |
amazon.aws.ec2_vpc_vpn: |
| 192 |
state: "present" |
| 193 |
filters: |
| 194 |
cidr: "194.168.1.0/24" |
| 195 |
tag-keys: |
| 196 |
- "Ansible" |
| 197 |
- "Other" |
| 198 |
tags: |
| 199 |
New: "Tag" |
| 200 |
purge_tags: true |
| 201 |
static_only: true |
| 202 |
|
| 203 |
- name: Set up VPN with tunnel options utilizing 'TunnelInsideCidr' only |
| 204 |
amazon.aws.ec2_vpc_vpn: |
| 205 |
state: "present" |
| 206 |
filters: |
| 207 |
vpn: "vpn-XXXXXXXX" |
| 208 |
static_only: true |
| 209 |
tunnel_options: |
| 210 |
- TunnelInsideCidr: "169.254.100.1/30" |
| 211 |
- TunnelInsideCidr: "169.254.100.5/30" |
| 212 |
|
| 213 |
- name: Add routes and remove any preexisting ones |
| 214 |
amazon.aws.ec2_vpc_vpn: |
| 215 |
state: "present" |
| 216 |
filters: |
| 217 |
vpn: "vpn-XXXXXXXX" |
| 218 |
routes: |
| 219 |
- "195.168.2.0/24" |
| 220 |
- "196.168.2.0/24" |
| 221 |
purge_routes: true |
| 222 |
|
| 223 |
- name: Remove all routes |
| 224 |
amazon.aws.ec2_vpc_vpn: |
| 225 |
state: "present" |
| 226 |
vpn_connection_id: "vpn-XXXXXXXX" |
| 227 |
routes: [] |
| 228 |
purge_routes: true |
| 229 |
|
| 230 |
- name: Delete a VPN identified by filters |
| 231 |
amazon.aws.ec2_vpc_vpn: |
| 232 |
state: "absent" |
| 233 |
filters: |
| 234 |
tags: |
| 235 |
Ansible: "Tag" |
| 236 |
""" |
| 237 |
|
| 238 |
RETURN = r""" |
| 239 |
changed: |
| 240 |
description: If the VPN connection has changed. |
| 241 |
type: bool |
| 242 |
returned: always |
| 243 |
sample: true |
| 244 |
customer_gateway_configuration: |
| 245 |
description: The configuration of the VPN connection. |
| 246 |
returned: O(state=present) |
| 247 |
type: str |
| 248 |
customer_gateway_id: |
| 249 |
description: The customer gateway connected via the connection. |
| 250 |
type: str |
| 251 |
returned: O(state=present) |
| 252 |
sample: "cgw-1220c87b" |
| 253 |
gateway_association_state: |
| 254 |
description: The current state of the gateway association. |
| 255 |
type: str |
| 256 |
returned: O(state=present) |
| 257 |
sample: "associated" |
| 258 |
vpn_gateway_id: |
| 259 |
description: The virtual private gateway connected via the connection. |
| 260 |
type: str |
| 261 |
returned: O(state=present) |
| 262 |
sample: "vgw-cb0ae2a2" |
| 263 |
transit_gateway_id: |
| 264 |
description: The transit gateway id to which the vpn connection can be attached. |
| 265 |
type: str |
| 266 |
returned: O(state=present) |
| 267 |
sample: "tgw-cb0ae2a2" |
| 268 |
options: |
| 269 |
description: The VPN connection options. |
| 270 |
type: list |
| 271 |
elements: dict |
| 272 |
returned: O(state=present) |
| 273 |
contains: |
| 274 |
static_routes_only: |
| 275 |
description: If the VPN connection only allows static routes. |
| 276 |
returned: O(state=present) |
| 277 |
type: bool |
| 278 |
sample: true |
| 279 |
enable_acceleration: |
| 280 |
description: Indicates whether acceleration is enabled for the VPN connection. |
| 281 |
returned: O(state=present) |
| 282 |
type: bool |
| 283 |
sample: false |
| 284 |
local_ipv4_network_cidr: |
| 285 |
description: The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. |
| 286 |
returned: O(state=present) |
| 287 |
type: str |
| 288 |
sample: "0.0.0.0/0" |
| 289 |
outside_ip_address_type: |
| 290 |
description: The external IP address of the VPN tunnel. |
| 291 |
returned: O(state=present) |
| 292 |
type: str |
| 293 |
sample: "PublicIpv4" |
| 294 |
remote_ipv4_network_cidr: |
| 295 |
description: The IPv4 CIDR on the Amazon Web Services side of the VPN connection. |
| 296 |
returned: O(state=present) |
| 297 |
type: str |
| 298 |
sample: "0.0.0.0/0" |
| 299 |
tunnel_inside_ip_version: |
| 300 |
description: Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. |
| 301 |
returned: O(state=present) |
| 302 |
type: str |
| 303 |
sample: "ipv4" |
| 304 |
tunnel_options: |
| 305 |
description: Indicates the VPN tunnel options. |
| 306 |
returned: O(state=present) |
| 307 |
type: list |
| 308 |
elements: dict |
| 309 |
sample: [{ |
| 310 |
"log_options": { |
| 311 |
"cloud_watch_log_options": { |
| 312 |
"log_enabled": false |
| 313 |
} |
| 314 |
}, |
| 315 |
"outside_ip_address": "34.225.101.10", |
| 316 |
"pre_shared_key": "8n7hnjNE8zhIt4VpMOIfcrw6XnUTHLW9", |
| 317 |
"tunnel_inside_cidr": "169.254.31.8/30" |
| 318 |
}] |
| 319 |
contains: |
| 320 |
log_options: |
| 321 |
description: Options for logging VPN tunnel activity. |
| 322 |
returned: O(state=present) |
| 323 |
type: dict |
| 324 |
contains: |
| 325 |
cloud_watch_log_options: |
| 326 |
description: Options for sending VPN tunnel logs to CloudWatch. |
| 327 |
type: dict |
| 328 |
returned: O(state=present) |
| 329 |
outside_ip_address: |
| 330 |
description: The external IP address of the VPN tunnel. |
| 331 |
type: str |
| 332 |
returned: O(state=present) |
| 333 |
pre_shared_key: |
| 334 |
description: |
| 335 |
- The pre-shared key (PSK) to establish initial authentication between the |
| 336 |
virtual private gateway and the customer gateway. |
| 337 |
type: str |
| 338 |
returned: O(state=present) |
| 339 |
tunnel_inside_cidr: |
| 340 |
description: The range of inside IPv4 addresses for the tunnel. |
| 341 |
type: str |
| 342 |
returned: O(state=present) |
| 343 |
routes: |
| 344 |
description: The routes of the VPN connection. |
| 345 |
type: list |
| 346 |
returned: O(state=present) |
| 347 |
sample: [{ |
| 348 |
"destination_cidr_block": "192.168.1.0/24", |
| 349 |
"state": "available" |
| 350 |
}] |
| 351 |
contains: |
| 352 |
destination_cidr_block: |
| 353 |
description: |
| 354 |
- The CIDR block associated with the local subnet of the customer data center. |
| 355 |
type: str |
| 356 |
returned: O(state=present) |
| 357 |
source: |
| 358 |
description: Indicates how the routes were provided. |
| 359 |
type: str |
| 360 |
returned: O(state=present) |
| 361 |
state: |
| 362 |
description: The current state of the static route. |
| 363 |
type: str |
| 364 |
returned: O(state=present) |
| 365 |
state: |
| 366 |
description: The status of the VPN connection. |
| 367 |
type: str |
| 368 |
returned: O(state=present) |
| 369 |
sample: "available" |
| 370 |
tags: |
| 371 |
description: The tags associated with the connection. |
| 372 |
type: dict |
| 373 |
returned: O(state=present) |
| 374 |
sample: { |
| 375 |
"name": "ansible-test", |
| 376 |
"other": "tag" |
| 377 |
} |
| 378 |
type: |
| 379 |
description: The type of VPN connection (currently only ipsec.1 is available). |
| 380 |
type: str |
| 381 |
returned: O(state=present) |
| 382 |
sample: "ipsec.1" |
| 383 |
vgw_telemetry: |
| 384 |
type: list |
| 385 |
returned: O(state=present) |
| 386 |
description: The telemetry for the VPN tunnel. |
| 387 |
sample: [{ |
| 388 |
"accepted_route_count": 0, |
| 389 |
"last_status_change": "2024-09-30T13:12:33+00:00", |
| 390 |
"outside_ip_address": "34.225.101.10", |
| 391 |
"status": "DOWN", |
| 392 |
"status_message": "IPSEC IS DOWN" |
| 393 |
}] |
| 394 |
contains: |
| 395 |
accepted_route_count: |
| 396 |
type: int |
| 397 |
returned: O(state=present) |
| 398 |
description: The number of accepted routes. |
| 399 |
last_status_change: |
| 400 |
type: str |
| 401 |
returned: O(state=present) |
| 402 |
description: The date and time of the last change in status. |
| 403 |
outside_ip_address: |
| 404 |
type: str |
| 405 |
returned: O(state=present) |
| 406 |
description: |
| 407 |
- The Internet-routable IP address of the virtual private gateway's outside interface. |
| 408 |
status: |
| 409 |
type: str |
| 410 |
returned: O(state=present) |
| 411 |
description: The status of the VPN tunnel. |
| 412 |
status_message: |
| 413 |
type: str |
| 414 |
returned: O(state=present) |
| 415 |
description: If an error occurs, a description of the error. |
| 416 |
certificate_arn: |
| 417 |
description: The Amazon Resource Name of the virtual private gateway tunnel endpoint certificate. |
| 418 |
returned: when a private certificate is used for authentication |
| 419 |
type: str |
| 420 |
sample: "arn:aws:acm:us-east-1:123456789012:certificate/c544d8ce-20b8-4fff-98b0-example" |
| 421 |
vpn_connection_id: |
| 422 |
description: The identifier for the VPN connection. |
| 423 |
type: str |
| 424 |
returned: O(state=present) |
| 425 |
sample: "vpn-781e0e19" |
| 426 |
""" |
| 427 |
|
| 428 |
try: |
| 429 |
from botocore.exceptions import WaiterError |
| 430 |
except ImportError: |
| 431 |
pass # Handled by AnsibleAWSModule |
| 432 |
|
| 433 |
from typing import Any |
| 434 |
from typing import Dict |
| 435 |
from typing import List |
| 436 |
from typing import NoReturn |
| 437 |
from typing import Optional |
| 438 |
from typing import Tuple |
| 439 |
from typing import Union |
| 440 |
|
| 441 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 442 |
from ansible.module_utils.common.text.converters import to_text |
| 443 |
|
| 444 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error |
| 445 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_vpn_connection |
| 446 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_vpn_connection_route |
| 447 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_vpn_connection |
| 448 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_vpn_connection_route |
| 449 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_vpn_connections |
| 450 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags |
| 451 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 452 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 453 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags |
| 454 |
|
| 455 |
|
| 456 |
def find_vpn_connection( |
| 457 |
client, module: AnsibleAWSModule, vpn_connection_id: Optional[str] = None |
| 458 |
) -> Union[None, Dict[str, Any]]: |
| 459 |
"""Looks for a unique VPN connection. Uses find_connection_response() to return the connection found, None, |
| 460 |
or raise an error if there were multiple viable connections.""" |
| 461 |
|
| 462 |
filters = module.params.get("filters") |
| 463 |
params: Dict[str, Any] = {} |
| 464 |
|
| 465 |
# vpn_connection_id may be provided via module option; takes precedence over any filter values |
| 466 |
if not vpn_connection_id and module.params.get("vpn_connection_id"): |
| 467 |
vpn_connection_id = module.params["vpn_connection_id"] |
| 468 |
|
| 469 |
if not isinstance(vpn_connection_id, list) and vpn_connection_id: |
| 470 |
vpn_connection_id = [to_text(vpn_connection_id)] |
| 471 |
elif isinstance(vpn_connection_id, list): |
| 472 |
vpn_connection_id = [to_text(connection) for connection in vpn_connection_id] |
| 473 |
|
| 474 |
formatted_filter: List = [] |
| 475 |
# if vpn_connection_id is provided it will take precedence over any filters since it is a unique identifier |
| 476 |
if not vpn_connection_id: |
| 477 |
formatted_filter = create_filter(module, filters) |
| 478 |
|
| 479 |
if vpn_connection_id: |
| 480 |
params["VpnConnectionIds"] = vpn_connection_id |
| 481 |
params["Filters"] = formatted_filter |
| 482 |
|
| 483 |
# see if there is a unique matching connection |
| 484 |
try: |
| 485 |
existing_conn = describe_vpn_connections(client, **params) |
| 486 |
except AnsibleEC2Error as e: |
| 487 |
module.fail_json_aws(e, msg="Failed while describing VPN connection.") |
| 488 |
|
| 489 |
return find_connection_response(module, connections=existing_conn) |
| 490 |
|
| 491 |
|
| 492 |
def add_routes(client, module: AnsibleAWSModule, vpn_connection_id: str, routes_to_add: List[Dict[str, Any]]) -> bool: |
| 493 |
changed: bool = False |
| 494 |
for route in routes_to_add: |
| 495 |
try: |
| 496 |
changed |= create_vpn_connection_route(client, vpn_connection_id, route) |
| 497 |
except AnsibleEC2Error as e: |
| 498 |
module.fail_json_aws(e, msg=f"Failed while adding route {route} to the VPN connection {vpn_connection_id}.") |
| 499 |
return changed |
| 500 |
|
| 501 |
|
| 502 |
def remove_routes( |
| 503 |
client, module: AnsibleAWSModule, vpn_connection_id: str, routes_to_remove: List[Dict[str, Any]] |
| 504 |
) -> bool: |
| 505 |
changed: bool = False |
| 506 |
for route in routes_to_remove: |
| 507 |
try: |
| 508 |
changed |= delete_vpn_connection_route(client, vpn_connection_id, route) |
| 509 |
except AnsibleEC2Error as e: |
| 510 |
module.fail_json_aws(e, msg=f"Failed to remove route {route} from the VPN connection {vpn_connection_id}.") |
| 511 |
return changed |
| 512 |
|
| 513 |
|
| 514 |
def create_filter(module, provided_filters: Dict[str, Any]) -> List[Dict[str, Any]]: |
| 515 |
"""Creates a filter using the user-specified parameters and unmodifiable options that may have been specified in the task""" |
| 516 |
|
| 517 |
boto3ify_filter = { |
| 518 |
"cgw-config": "customer-gateway-configuration", |
| 519 |
"static-routes-only": "option.static-routes-only", |
| 520 |
"cidr": "route.destination-cidr-block", |
| 521 |
"bgp": "bgp-asn", |
| 522 |
"vpn": "vpn-connection-id", |
| 523 |
"vgw": "vpn-gateway-id", |
| 524 |
"tag-keys": "tag-key", |
| 525 |
"tag-values": "tag-value", |
| 526 |
"tags": "tag", |
| 527 |
"cgw": "customer-gateway-id", |
| 528 |
} |
| 529 |
|
| 530 |
# unmodifiable options and their filter name counterpart |
| 531 |
param_to_filter = { |
| 532 |
"customer_gateway_id": "customer-gateway-id", |
| 533 |
"vpn_gateway_id": "vpn-gateway-id", |
| 534 |
"transit_gateway_id": "transit-gateway-id", |
| 535 |
"vpn_connection_id": "vpn-connection-id", |
| 536 |
} |
| 537 |
|
| 538 |
flat_filter_dict = {} |
| 539 |
formatted_filter: List = [] |
| 540 |
|
| 541 |
for raw_param in dict(provided_filters): |
| 542 |
# fix filter names to be recognized by boto3 |
| 543 |
if raw_param in boto3ify_filter: |
| 544 |
param = boto3ify_filter[raw_param] |
| 545 |
provided_filters[param] = provided_filters.pop(raw_param) |
| 546 |
elif raw_param in list(boto3ify_filter.items()): |
| 547 |
param = raw_param |
| 548 |
else: |
| 549 |
module.fail_json(msg=f"{raw_param} is not a valid filter.") |
| 550 |
|
| 551 |
# reformat filters with special formats |
| 552 |
if param == "tag": |
| 553 |
for key in provided_filters[param]: |
| 554 |
formatted_key = "tag:" + key |
| 555 |
if isinstance(provided_filters[param][key], list): |
| 556 |
flat_filter_dict[formatted_key] = str(provided_filters[param][key]) |
| 557 |
else: |
| 558 |
flat_filter_dict[formatted_key] = [str(provided_filters[param][key])] |
| 559 |
elif param == "option.static-routes-only": |
| 560 |
flat_filter_dict[param] = [str(provided_filters[param]).lower()] |
| 561 |
else: |
| 562 |
if isinstance(provided_filters[param], list): |
| 563 |
flat_filter_dict[param] = provided_filters[param] |
| 564 |
else: |
| 565 |
flat_filter_dict[param] = [str(provided_filters[param])] |
| 566 |
|
| 567 |
# if customer_gateway, vpn_gateway, or vpn_connection was specified in the task but not the filter, add it |
| 568 |
for param, param_value in param_to_filter.items(): |
| 569 |
if param_value not in flat_filter_dict and module.params.get(param): |
| 570 |
flat_filter_dict[param_value] = [module.params.get(param)] |
| 571 |
|
| 572 |
# change the flat dict into something boto3 will understand |
| 573 |
formatted_filter = [{"Name": key, "Values": value} for key, value in flat_filter_dict.items()] |
| 574 |
|
| 575 |
return formatted_filter |
| 576 |
|
| 577 |
|
| 578 |
def find_connection_response(module, connections: Optional[List[Dict[str, Any]]] = None) -> Optional[Dict[str, Any]]: |
| 579 |
"""Determine if there is a viable unique match in the connections described. Returns the unique VPN connection if one is found, |
| 580 |
returns None if the connection does not exist, raise an error if multiple matches are found.""" |
| 581 |
|
| 582 |
# Found no connections |
| 583 |
if not connections: |
| 584 |
return None |
| 585 |
|
| 586 |
# Too many results |
| 587 |
elif connections and len(connections) > 1: |
| 588 |
viable = [] |
| 589 |
for each in connections: |
| 590 |
# deleted connections are not modifiable |
| 591 |
if each["State"] not in ("deleted", "deleting"): |
| 592 |
viable.append(each) |
| 593 |
if len(viable) == 1: |
| 594 |
# Found one viable result; return unique match |
| 595 |
return viable[0] |
| 596 |
elif len(viable) == 0: |
| 597 |
# Found a result but it was deleted already; since there was only one viable result create a new one |
| 598 |
return None |
| 599 |
else: |
| 600 |
module.fail_json( |
| 601 |
msg=( |
| 602 |
"More than one matching VPN connection was found. " |
| 603 |
"To modify or delete a VPN please specify vpn_connection_id or add filters." |
| 604 |
) |
| 605 |
) |
| 606 |
|
| 607 |
# Found unique match |
| 608 |
elif connections and len(connections) == 1: |
| 609 |
# deleted connections are not modifiable |
| 610 |
if connections[0]["State"] not in ("deleted", "deleting"): |
| 611 |
return connections[0] |
| 612 |
|
| 613 |
|
| 614 |
def create_connection( |
| 615 |
client, |
| 616 |
module: AnsibleAWSModule, |
| 617 |
customer_gateway_id: Optional[str], |
| 618 |
static_only: Optional[bool], |
| 619 |
vpn_gateway_id: str, |
| 620 |
transit_gateway_id: str, |
| 621 |
connection_type: Optional[str], |
| 622 |
max_attempts: Optional[int], |
| 623 |
delay: Optional[int], |
| 624 |
local_ipv4_network_cidr: Optional[str], |
| 625 |
tunnel_options: Optional[List[Dict[str, Any]]] = None, |
| 626 |
) -> Dict[str, Any]: |
| 627 |
"""Creates a VPN connection""" |
| 628 |
|
| 629 |
options = {"StaticRoutesOnly": static_only, "LocalIpv4NetworkCidr": local_ipv4_network_cidr} |
| 630 |
|
| 631 |
if tunnel_options and len(tunnel_options) <= 2: |
| 632 |
t_opt = [] |
| 633 |
for m in tunnel_options: |
| 634 |
# See Boto3 docs regarding 'create_vpn_connection' |
| 635 |
# tunnel options for allowed 'TunnelOptions' keys. |
| 636 |
if not isinstance(m, dict): |
| 637 |
raise TypeError("non-dict list member") |
| 638 |
t_opt.append(m) |
| 639 |
if t_opt: |
| 640 |
options["TunnelOptions"] = t_opt |
| 641 |
|
| 642 |
if not (customer_gateway_id and (vpn_gateway_id or transit_gateway_id)): |
| 643 |
module.fail_json( |
| 644 |
msg=( |
| 645 |
"No matching connection was found. To create a new connection you must provide " |
| 646 |
"customer_gateway_id and one of either transit_gateway_id or vpn_gateway_id." |
| 647 |
) |
| 648 |
) |
| 649 |
vpn_connection_params: Dict[str, Any] = { |
| 650 |
"Type": connection_type, |
| 651 |
"CustomerGatewayId": customer_gateway_id, |
| 652 |
"Options": options, |
| 653 |
} |
| 654 |
|
| 655 |
if vpn_gateway_id: |
| 656 |
vpn_connection_params["VpnGatewayId"] = vpn_gateway_id |
| 657 |
if transit_gateway_id: |
| 658 |
vpn_connection_params["TransitGatewayId"] = transit_gateway_id |
| 659 |
|
| 660 |
try: |
| 661 |
vpn = create_vpn_connection(client, **vpn_connection_params) |
| 662 |
client.get_waiter("vpn_connection_available").wait( |
| 663 |
VpnConnectionIds=[vpn["VpnConnectionId"]], |
| 664 |
WaiterConfig={"Delay": delay, "MaxAttempts": max_attempts}, |
| 665 |
) |
| 666 |
except WaiterError as e: |
| 667 |
module.fail_json_aws(e, msg=f"Failed to wait for VPN connection {vpn['VpnConnectionId']} to be available") |
| 668 |
except AnsibleEC2Error as e: |
| 669 |
module.fail_json_aws(e, msg="Failed to create VPN connection") |
| 670 |
|
| 671 |
return vpn |
| 672 |
|
| 673 |
|
| 674 |
def delete_connection(client, module: AnsibleAWSModule, vpn_connection_id: str) -> NoReturn: |
| 675 |
"""Deletes a VPN connection""" |
| 676 |
|
| 677 |
delay = module.params.get("delay") |
| 678 |
max_attempts = module.params.get("wait_timeout") // delay |
| 679 |
|
| 680 |
try: |
| 681 |
delete_vpn_connection(client, vpn_connection_id) |
| 682 |
client.get_waiter("vpn_connection_deleted").wait( |
| 683 |
VpnConnectionIds=[vpn_connection_id], WaiterConfig={"Delay": delay, "MaxAttempts": max_attempts} |
| 684 |
) |
| 685 |
except WaiterError as e: |
| 686 |
module.fail_json_aws(e, msg=f"Failed to wait for VPN connection {vpn_connection_id} to be removed") |
| 687 |
except AnsibleEC2Error as e: |
| 688 |
module.fail_json_aws(e, msg=f"Failed to delete the VPN connection: {vpn_connection_id}") |
| 689 |
|
| 690 |
|
| 691 |
def check_for_routes_update(client, module: AnsibleAWSModule, vpn_connection_id: str) -> Dict[str, Any]: |
| 692 |
"""Determines if there are any routes that need to be updated. Ensures non-modifiable attributes aren't expected to change.""" |
| 693 |
routes = module.params.get("routes") |
| 694 |
purge_routes = module.params.get("purge_routes") |
| 695 |
|
| 696 |
vpn_connection = find_vpn_connection(client, module, vpn_connection_id) |
| 697 |
current_attrs = camel_dict_to_snake_dict(vpn_connection) |
| 698 |
|
| 699 |
# Initialize changes dict |
| 700 |
changes: Dict[str, Any] = {"routes_to_add": [], "routes_to_remove": []} |
| 701 |
|
| 702 |
# Get changes to routes |
| 703 |
if "Routes" in vpn_connection: |
| 704 |
current_routes = [route["DestinationCidrBlock"] for route in vpn_connection["Routes"]] |
| 705 |
if purge_routes: |
| 706 |
changes["routes_to_remove"] = [old_route for old_route in current_routes if old_route not in routes] |
| 707 |
changes["routes_to_add"] = [new_route for new_route in routes if new_route not in current_routes] |
| 708 |
|
| 709 |
# Check if nonmodifiable attributes are attempted to be modified |
| 710 |
for attribute in current_attrs: |
| 711 |
if attribute in ("tags", "routes", "state"): |
| 712 |
continue |
| 713 |
if attribute == "options": |
| 714 |
will_be = module.params.get("static_only") |
| 715 |
is_now = bool(current_attrs[attribute]["static_routes_only"]) |
| 716 |
attribute = "static_only" |
| 717 |
elif attribute == "type": |
| 718 |
will_be = module.params.get("connection_type") |
| 719 |
is_now = current_attrs[attribute] |
| 720 |
else: |
| 721 |
is_now = current_attrs[attribute] |
| 722 |
will_be = module.params.get(attribute) |
| 723 |
|
| 724 |
if will_be is not None and to_text(will_be) != to_text(is_now): |
| 725 |
module.fail_json( |
| 726 |
msg=( |
| 727 |
f"You cannot modify {attribute}, the current value of which is {is_now}. Modifiable VPN connection" |
| 728 |
f" attributes are tags and routes. The value you tried to change it to is {will_be}." |
| 729 |
) |
| 730 |
) |
| 731 |
|
| 732 |
return changes |
| 733 |
|
| 734 |
|
| 735 |
def make_changes(client, module: AnsibleAWSModule, vpn_connection_id: str, changes: Dict[str, Any]) -> bool: |
| 736 |
"""changes is a dict with the keys 'routes_to_add', 'routes_to_remove', |
| 737 |
the values of which are lists (generated by check_for_routes_update()). |
| 738 |
""" |
| 739 |
changed: bool = False |
| 740 |
|
| 741 |
if module.params.get("tags") is not None: |
| 742 |
changed |= ensure_ec2_tags( |
| 743 |
client, |
| 744 |
module, |
| 745 |
vpn_connection_id, |
| 746 |
resource_type="vpn-connection", |
| 747 |
tags=module.params.get("tags"), |
| 748 |
purge_tags=module.params.get("purge_tags"), |
| 749 |
) |
| 750 |
|
| 751 |
if changes["routes_to_add"]: |
| 752 |
changed |= add_routes(client, module, vpn_connection_id, changes["routes_to_add"]) |
| 753 |
|
| 754 |
if changes["routes_to_remove"]: |
| 755 |
changed |= remove_routes(client, module, vpn_connection_id, changes["routes_to_remove"]) |
| 756 |
|
| 757 |
return changed |
| 758 |
|
| 759 |
|
| 760 |
def get_check_mode_results( |
| 761 |
module_params: Dict[str, Any], vpn_connection_id: Optional[str] = None, current_state: Optional[str] = None |
| 762 |
) -> Tuple[bool, Dict[str, Any]]: |
| 763 |
"""Returns the changes that would be made to a VPN Connection""" |
| 764 |
changed: bool = False |
| 765 |
results: Dict[str, Any] = { |
| 766 |
"customer_gateway_configuration": "", |
| 767 |
"customer_gateway_id": module_params.get("customer_gateway_id"), |
| 768 |
"vpn_gateway_id": module_params.get("vpn_gateway_id"), |
| 769 |
"transit_gateway_id": module_params.get("transit_gateway_id"), |
| 770 |
"options": {"static_routes_only": module_params.get("static_only")}, |
| 771 |
"routes": [module_params.get("routes")], |
| 772 |
} |
| 773 |
|
| 774 |
present_tags = module_params.get("tags") |
| 775 |
# get combined current tags and tags to set |
| 776 |
if present_tags is None: |
| 777 |
pass |
| 778 |
elif current_state and "Tags" in current_state: |
| 779 |
current_tags = boto3_tag_list_to_ansible_dict(current_state["Tags"]) |
| 780 |
tags_to_add, tags_to_remove = compare_aws_tags(current_tags, present_tags, module_params.get("purge_tags")) |
| 781 |
changed |= bool(tags_to_remove) or bool(tags_to_add) |
| 782 |
if module_params.get("purge_tags"): |
| 783 |
current_tags = {} |
| 784 |
current_tags.update(present_tags) |
| 785 |
results["tags"] = current_tags |
| 786 |
elif module_params.get("tags"): |
| 787 |
changed = True |
| 788 |
|
| 789 |
if present_tags: |
| 790 |
results["tags"] = present_tags |
| 791 |
|
| 792 |
# get combined current routes and routes to add |
| 793 |
present_routes = module_params.get("routes") |
| 794 |
if current_state and "Routes" in current_state: |
| 795 |
current_routes = [route["DestinationCidrBlock"] for route in current_state["Routes"]] |
| 796 |
if module_params.get("purge_routes"): |
| 797 |
if set(current_routes) != set(present_routes): |
| 798 |
changed = True |
| 799 |
elif set(present_routes) != set(current_routes): |
| 800 |
if not set(present_routes) < set(current_routes): |
| 801 |
changed = True |
| 802 |
present_routes.extend([route for route in current_routes if route not in present_routes]) |
| 803 |
elif module_params.get("routes"): |
| 804 |
changed = True |
| 805 |
results["routes"] = [{"destination_cidr_block": cidr, "state": "available"} for cidr in present_routes] |
| 806 |
|
| 807 |
# return the vpn_connection_id if it's known |
| 808 |
if vpn_connection_id: |
| 809 |
results["vpn_connection_id"] = vpn_connection_id |
| 810 |
else: |
| 811 |
changed = True |
| 812 |
results["vpn_connection_id"] = "vpn-XXXXXXXX" |
| 813 |
|
| 814 |
return changed, results |
| 815 |
|
| 816 |
|
| 817 |
def ensure_present( |
| 818 |
client, module: AnsibleAWSModule, vpn_connection: Optional[Dict[str, Any]] |
| 819 |
) -> Tuple[bool, Dict[str, Any]]: |
| 820 |
"""Creates and adds tags to a VPN connection. If the connection already exists update tags.""" |
| 821 |
changed: bool = False |
| 822 |
delay = module.params.get("delay") |
| 823 |
max_attempts = module.params.get("wait_timeout") // delay |
| 824 |
|
| 825 |
# No match but vpn_connection_id was specified. |
| 826 |
if not vpn_connection and module.params.get("vpn_connection_id"): |
| 827 |
module.fail_json(msg="There is no VPN connection available or pending with that id. Did you delete it?") |
| 828 |
|
| 829 |
# Unique match was found. Check if attributes provided differ. |
| 830 |
elif vpn_connection: |
| 831 |
vpn_connection_id = vpn_connection["VpnConnectionId"] |
| 832 |
# check_for_update returns a dict with the keys routes_to_add, routes_to_remove |
| 833 |
changes = check_for_routes_update(client, module, vpn_connection_id) |
| 834 |
|
| 835 |
if module.check_mode: |
| 836 |
return get_check_mode_results(module.params, vpn_connection_id, current_state=vpn_connection) |
| 837 |
|
| 838 |
changed |= make_changes(client, module, vpn_connection_id, changes) |
| 839 |
|
| 840 |
# No match was found. Create and tag a connection and add routes. |
| 841 |
else: |
| 842 |
changed = True |
| 843 |
|
| 844 |
if module.check_mode: |
| 845 |
return get_check_mode_results(module.params) |
| 846 |
|
| 847 |
vpn_connection = create_connection( |
| 848 |
client, |
| 849 |
module, |
| 850 |
customer_gateway_id=module.params.get("customer_gateway_id"), |
| 851 |
static_only=module.params.get("static_only"), |
| 852 |
vpn_gateway_id=module.params.get("vpn_gateway_id"), |
| 853 |
transit_gateway_id=module.params.get("transit_gateway_id"), |
| 854 |
connection_type=module.params.get("connection_type"), |
| 855 |
local_ipv4_network_cidr=module.params.get("local_ipv4_network_cidr"), |
| 856 |
tunnel_options=module.params.get("tunnel_options"), |
| 857 |
max_attempts=max_attempts, |
| 858 |
delay=delay, |
| 859 |
) |
| 860 |
|
| 861 |
changes = check_for_routes_update(client, module, vpn_connection["VpnConnectionId"]) |
| 862 |
make_changes(client, module, vpn_connection["VpnConnectionId"], changes) |
| 863 |
|
| 864 |
# get latest version if a change has been made and make tags output nice before returning it |
| 865 |
if vpn_connection: |
| 866 |
vpn_connection = find_vpn_connection(client, module, vpn_connection["VpnConnectionId"]) |
| 867 |
if "Tags" in vpn_connection: |
| 868 |
vpn_connection["Tags"] = boto3_tag_list_to_ansible_dict(vpn_connection["Tags"]) |
| 869 |
|
| 870 |
return (changed, vpn_connection) |
| 871 |
|
| 872 |
|
| 873 |
def ensure_absent(client, module: AnsibleAWSModule, vpn_connection: Dict[str, Any]) -> bool: |
| 874 |
"""Deletes a VPN connection if it exists.""" |
| 875 |
changed: bool = False |
| 876 |
|
| 877 |
if vpn_connection: |
| 878 |
changed = True |
| 879 |
|
| 880 |
if module.check_mode: |
| 881 |
return changed |
| 882 |
|
| 883 |
delete_connection(client, module, vpn_connection["VpnConnectionId"]) |
| 884 |
|
| 885 |
return changed |
| 886 |
|
| 887 |
|
| 888 |
def main(): |
| 889 |
argument_spec = dict( |
| 890 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 891 |
filters=dict(type="dict", default={}), |
| 892 |
vpn_gateway_id=dict(type="str"), |
| 893 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 894 |
connection_type=dict(default="ipsec.1", type="str"), |
| 895 |
transit_gateway_id=dict(type="str"), |
| 896 |
local_ipv4_network_cidr=dict(type="str", default="0.0.0.0/0"), |
| 897 |
tunnel_options=dict( |
| 898 |
no_log=True, |
| 899 |
type="list", |
| 900 |
default=[], |
| 901 |
elements="dict", |
| 902 |
options=dict( |
| 903 |
TunnelInsideCidr=dict(type="str"), |
| 904 |
TunnelInsideIpv6Cidr=dict(type="str"), |
| 905 |
PreSharedKey=dict(type="str", no_log=True), |
| 906 |
), |
| 907 |
), |
| 908 |
static_only=dict(default=False, type="bool"), |
| 909 |
customer_gateway_id=dict(type="str"), |
| 910 |
vpn_connection_id=dict(type="str"), |
| 911 |
purge_tags=dict(type="bool", default=True), |
| 912 |
routes=dict(type="list", default=[], elements="str"), |
| 913 |
purge_routes=dict(type="bool", default=False), |
| 914 |
wait_timeout=dict(type="int", default=600), |
| 915 |
delay=dict(type="int", default=15), |
| 916 |
) |
| 917 |
mutually_exclusive = [ |
| 918 |
["vpn_gateway_id", "transit_gateway_id"], |
| 919 |
] |
| 920 |
|
| 921 |
module = AnsibleAWSModule( |
| 922 |
argument_spec=argument_spec, |
| 923 |
supports_check_mode=True, |
| 924 |
mutually_exclusive=mutually_exclusive, |
| 925 |
) |
| 926 |
client = module.client("ec2") |
| 927 |
|
| 928 |
response: Dict[str, Any] = {} |
| 929 |
state = module.params.get("state") |
| 930 |
|
| 931 |
vpn_connection = find_vpn_connection(client, module) |
| 932 |
|
| 933 |
if state == "present": |
| 934 |
changed, response = ensure_present(client, module, vpn_connection) |
| 935 |
elif state == "absent": |
| 936 |
changed = ensure_absent(client, module, vpn_connection) |
| 937 |
|
| 938 |
module.exit_json(changed=changed, **camel_dict_to_snake_dict(response)) |
| 939 |
|
| 940 |
|
| 941 |
if __name__ == "__main__": |
| 942 |
main() |