Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_vpc_endpoint.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 module: ec2_vpc_endpoint
9 short_description: Create and delete AWS VPC endpoints
10 version_added: 1.0.0
11 description:
12 - Creates AWS VPC endpoints.
13 - Deletes AWS VPC endpoints.
14 - This module supports check mode.
15 options:
16 vpc_id:
17 description:
18 - Required when creating a VPC endpoint.
19 required: false
20 type: str
21 vpc_endpoint_type:
22 description:
23 - The type of endpoint.
24 required: false
25 default: Gateway
26 choices: [ "Interface", "Gateway", "GatewayLoadBalancer" ]
27 type: str
28 version_added: 1.5.0
29 vpc_endpoint_subnets:
30 description:
31 - The list of subnets to attach to the endpoint.
32 - Requires O(vpc_endpoint_type=GatewayLoadBalancer) or O(vpc_endpoint_type=Interface).
33 required: false
34 type: list
35 elements: str
36 version_added: 2.1.0
37 vpc_endpoint_security_groups:
38 description:
39 - The list of security groups to attach to the endpoint.
40 - Requires O(vpc_endpoint_type=GatewayLoadBalancer) or O(vpc_endpoint_type=Interface).
41 required: false
42 type: list
43 elements: str
44 version_added: 2.1.0
45 service:
46 description:
47 - An AWS supported VPC endpoint service. Use the M(amazon.aws.ec2_vpc_endpoint_info)
48 module to describe the supported endpoint services.
49 - Required when creating an endpoint.
50 required: false
51 type: str
52 policy:
53 description:
54 - A properly formatted JSON policy as string, see
55 U(https://github.com/ansible/ansible/issues/7005#issuecomment-42894813).
56 - Option when creating an endpoint. If not provided AWS will
57 utilise a default policy which provides full access to the service.
58 required: false
59 type: json
60 state:
61 description:
62 - V(present) to ensure resource is created.
63 - V(absent) to remove resource.
64 required: false
65 default: present
66 choices: [ "present", "absent" ]
67 type: str
68 wait:
69 description:
70 - When specified, will wait for status to reach available for O(state=present).
71 - Unfortunately this is ignored for delete actions due to a difference in
72 behaviour from AWS.
73 required: false
74 default: false
75 type: bool
76 wait_timeout:
77 description:
78 - Used in conjunction with O(wait).
79 - Number of seconds to wait for status.
80 - Unfortunately this is ignored for delete actions due to a difference in
81 behaviour from AWS.
82 required: false
83 default: 320
84 type: int
85 route_table_ids:
86 description:
87 - List of one or more route table IDs to attach to the endpoint.
88 - A route is added to the route table with the destination of the
89 endpoint if provided.
90 - Route table IDs are only valid for Gateway endpoints.
91 required: false
92 type: list
93 elements: str
94 vpc_endpoint_id:
95 description:
96 - One or more VPC endpoint IDs to remove from the AWS account.
97 - Required if O(state=absent).
98 required: false
99 type: str
100 client_token:
101 description:
102 - Optional client token to ensure idempotency.
103 required: false
104 type: str
105 author:
106 - Karen Cheng (@Etherdaemon)
107 notes:
108 - Support for O(tags) and I(purge_tags) was added in release 1.5.0.
109 - The I(policy_file) paramater was removed in release 6.0.0 please use the
110 O(policy) option and the P(ansible.builtin.file#lookup) lookup plugin instead.
111 extends_documentation_fragment:
112 - amazon.aws.common.modules
113 - amazon.aws.region.modules
114 - amazon.aws.tags
115 - amazon.aws.boto3
116 """
117
118 EXAMPLES = r"""
119 # Note: These examples do not set authentication details, see the AWS Guide for details.
120
121 - name: Create new vpc endpoint with a json template for policy
122 amazon.aws.ec2_vpc_endpoint:
123 state: present
124 region: ap-southeast-2
125 vpc_id: vpc-12345678
126 service: com.amazonaws.ap-southeast-2.s3
127 policy: " {{ lookup( 'template', 'endpoint_policy.json.j2') }} "
128 route_table_ids:
129 - rtb-12345678
130 - rtb-87654321
131 register: new_vpc_endpoint
132
133 - name: Create new vpc endpoint with the default policy
134 amazon.aws.ec2_vpc_endpoint:
135 state: present
136 region: ap-southeast-2
137 vpc_id: vpc-12345678
138 service: com.amazonaws.ap-southeast-2.s3
139 route_table_ids:
140 - rtb-12345678
141 - rtb-87654321
142 register: new_vpc_endpoint
143
144 - name: Delete newly created vpc endpoint
145 amazon.aws.ec2_vpc_endpoint:
146 state: absent
147 vpc_endpoint_id: "{{ new_vpc_endpoint.result['VpcEndpointId'] }}"
148 region: ap-southeast-2
149 """
150
151 RETURN = r"""
152 endpoints:
153 description: The resulting endpoints from the module call.
154 returned: success
155 type: list
156 elements: dict
157 contains:
158 creation_timestamp:
159 description: The date and time that the endpoint was created.
160 returned: always
161 type: str
162 dns_entries:
163 description: List of DNS entires for the endpoint.
164 returned: always
165 type: list
166 elements: dict
167 contains:
168 dns_name:
169 description: The DNS name.
170 returned: always
171 type: str
172 hosted_zone_id:
173 description: The ID of the private hosted zone.
174 type: str
175 groups:
176 description: List of security groups associated with the network interface.
177 returned: always
178 type: list
179 elements: dict
180 contains:
181 group_id:
182 description: The ID of the security group.
183 returned: always
184 type: str
185 group_name:
186 description: The name of the security group.
187 returned: always
188 type: str
189 ip_address_type:
190 description: The IP address type for the endpoint.
191 type: str
192 network_interface_ids:
193 description: List of network interfaces for the endpoint.
194 returned: always
195 type: list
196 elements: str
197 owner_id:
198 description: The ID of the AWS account that owns the endpoint.
199 returned: always
200 type: str
201 policy_document:
202 description: The policy document associated with the endpoint.
203 returned: always
204 type: str
205 private_dns_enabled:
206 description: Indicates whether the VPC is associated with a private hosted zone.
207 returned: always
208 type: bool
209 requester_managed:
210 description: Indicated whether the endpoint is being managed by its service.
211 returned: always
212 type: bool
213 route_table_ids:
214 description: List of route table IDs associated with the endpoint.
215 returned: always
216 type: list
217 elements: str
218 service_name:
219 description: The name of the service to which the endpoint is associated.
220 returned: always
221 type: str
222 state:
223 description: The state of the endpoint.
224 returned: always
225 type: str
226 subnet_ids:
227 description: List of subnets associated with the endpoint.
228 returned: always
229 type: list
230 tags:
231 description: List of tags associated with the endpoint.
232 returned: always
233 type: list
234 elements: dict
235 vpc_endpoint_id:
236 description: The ID of the endpoint.
237 returned: always
238 type: str
239 vpc_endpoint_type:
240 description: The type of endpoint.
241 returned: always
242 type: str
243 vpc_id:
244 description: The ID of the VPC.
245 returned: always
246 type: str
247 """
248
249 import datetime
250 import json
251 import traceback
252 from typing import Any
253 from typing import Dict
254 from typing import List
255 from typing import Optional
256 from typing import Tuple
257
258 try:
259 import botocore
260 except ImportError:
261 pass # Handled by AnsibleAWSModule
262
263 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
264
265 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
266 from ansible_collections.amazon.aws.plugins.module_utils.botocore import normalize_boto3_result
267 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
268 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_vpc_endpoint
269 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_vpc_endpoints
270 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_vpc_endpoints
271 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
272 from ansible_collections.amazon.aws.plugins.module_utils.exceptions import AnsibleAWSError
273 from ansible_collections.amazon.aws.plugins.module_utils.exceptions import is_ansible_aws_error_code
274 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
275 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
276 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
277
278
279 def get_endpoints(client, params: Dict[str, Any], endpoint_id: Optional[str] = None) -> List[Dict[str, Any]]:
280 api_params = dict()
281 if endpoint_id:
282 api_params["VpcEndpointIds"] = [endpoint_id]
283 else:
284 filters = list()
285 if params.get("service"):
286 filters.append({"Name": "service-name", "Values": [params.get("service")]})
287 if params.get("vpc_id"):
288 filters.append({"Name": "vpc-id", "Values": [params.get("vpc_id")]})
289 api_params["Filters"] = filters
290 result = describe_vpc_endpoints(client, **api_params)
291
292 # normalize iso datetime fields in result
293 normalized_result = normalize_boto3_result(result)
294 return normalized_result
295
296
297 def match_endpoints(route_table_ids, service_name, vpc_id, endpoint):
298 found = False
299 sorted_route_table_ids = []
300
301 if route_table_ids:
302 sorted_route_table_ids = sorted(route_table_ids)
303
304 if endpoint["VpcId"] == vpc_id and endpoint["ServiceName"] == service_name:
305 sorted_endpoint_rt_ids = sorted(endpoint["RouteTableIds"])
306 if sorted_endpoint_rt_ids == sorted_route_table_ids:
307 found = True
308 return found
309
310
311 def setup_creation(client, module: AnsibleAWSModule) -> Tuple[bool, Dict[str, Any]]:
312 endpoint_id = module.params.get("vpc_endpoint_id")
313 route_table_ids = module.params.get("route_table_ids")
314 service_name = module.params.get("service")
315 vpc_id = module.params.get("vpc_id")
316 changed = False
317
318 if not endpoint_id:
319 # Try to use the module parameters to match any existing endpoints
320 all_endpoints = get_endpoints(client, module.params, endpoint_id)
321 for endpoint in all_endpoints:
322 if match_endpoints(route_table_ids, service_name, vpc_id, endpoint):
323 endpoint_id = endpoint["VpcEndpointId"]
324 break
325
326 if endpoint_id:
327 # If we have an endpoint now, just ensure tags and exit
328 if module.params.get("tags"):
329 changed |= ensure_ec2_tags(
330 client,
331 module,
332 endpoint_id,
333 resource_type="vpc-endpoint",
334 tags=module.params.get("tags"),
335 purge_tags=module.params.get("purge_tags"),
336 )
337 normalized_result = get_endpoints(client, module.params, endpoint_id=endpoint_id)[0]
338 return changed, camel_dict_to_snake_dict(normalized_result, ignore_list=["Tags"])
339
340 changed, result = create_aws_vpc_endpoint(client, module)
341
342 return changed, camel_dict_to_snake_dict(result, ignore_list=["Tags"])
343
344
345 def create_aws_vpc_endpoint(client, module: AnsibleAWSModule) -> Tuple[bool, Dict[str, Any]]:
346 params = {}
347 changed = False
348 token_provided = False
349 params["VpcId"] = module.params.get("vpc_id")
350 params["VpcEndpointType"] = module.params.get("vpc_endpoint_type")
351 params["ServiceName"] = module.params.get("service")
352
353 if module.params.get("vpc_endpoint_type") != "Gateway" and module.params.get("route_table_ids"):
354 module.fail_json(msg="Route table IDs are only supported for Gateway type VPC Endpoint.")
355
356 if module.check_mode:
357 changed = True
358 result = "Would have created VPC Endpoint if not in check mode"
359 module.exit_json(changed=changed, result=result)
360
361 if module.params.get("route_table_ids"):
362 params["RouteTableIds"] = module.params.get("route_table_ids")
363
364 if module.params.get("vpc_endpoint_subnets"):
365 params["SubnetIds"] = module.params.get("vpc_endpoint_subnets")
366
367 if module.params.get("vpc_endpoint_security_groups"):
368 params["SecurityGroupIds"] = module.params.get("vpc_endpoint_security_groups")
369
370 if module.params.get("client_token"):
371 token_provided = True
372 request_time = datetime.datetime.now(datetime.timezone.utc)
373 params["ClientToken"] = module.params.get("client_token")
374
375 policy = None
376 if module.params.get("policy"):
377 try:
378 policy = json.loads(module.params.get("policy"))
379 except ValueError as e:
380 module.fail_json(msg=str(e), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
381
382 if policy:
383 params["PolicyDocument"] = json.dumps(policy)
384
385 if module.params.get("tags"):
386 params["TagSpecifications"] = boto3_tag_specifications(module.params.get("tags"), ["vpc-endpoint"])
387
388 try:
389 changed = True
390 result = create_vpc_endpoint(client, **params)
391 if token_provided and (request_time > result["creation_timestamp"].replace(tzinfo=None)):
392 changed = False
393 elif module.params.get("wait") and not module.check_mode:
394 wait_for_resource_state(
395 client,
396 module,
397 "vpc_endpoint_exists",
398 delay=15,
399 max_attempts=int(module.params.get("wait_timeout") // 15),
400 VpcEndpointIds=[result["VpcEndpointId"]],
401 )
402
403 except is_ansible_aws_error_code("IdempotentParameterMismatch"):
404 module.fail_json(msg="IdempotentParameterMismatch - updates of endpoints are not allowed by the API")
405 except is_ansible_aws_error_code("RouteAlreadyExists"): # pylint: disable=duplicate-except
406 module.fail_json(msg="RouteAlreadyExists for one of the route tables - update is not allowed by the API")
407 except AnsibleAWSError as e: # pylint: disable=duplicate-except
408 module.fail_json_aws(e, msg="Failed to create VPC Endpoint.")
409
410 # describe and normalize iso datetime fields in result after adding tags
411 normalized_result = get_endpoints(client, module.params, endpoint_id=result["VpcEndpointId"])[0]
412 return changed, normalized_result
413
414
415 def setup_removal(client, module: AnsibleAWSModule) -> Tuple[bool, Dict[str, Any]]:
416 changed = False
417
418 if module.check_mode:
419 try:
420 result = {"msg": "Would have deleted VPC Endpoint if not in check mode"}
421 changed = True
422 exists = describe_vpc_endpoints(client, VpcEndpointIds=[module.params.get("vpc_endpoint_id")])
423 if not exists:
424 result = {"msg": "Endpoint does not exist, nothing to delete."}
425 changed = False
426 except AnsibleEC2Error as e:
427 module.fail_json_aws(e, msg="Failed to get endpoints")
428
429 return changed, result
430
431 vpc_endpoint_ids = module.params.get("vpc_endpoint_id")
432 if isinstance(vpc_endpoint_ids, str):
433 vpc_endpoint_ids = [vpc_endpoint_ids]
434
435 try:
436 result = delete_vpc_endpoints(client, vpc_endpoint_ids)
437 if len(result) < len(vpc_endpoint_ids):
438 changed = True
439 # For some reason delete_vpc_endpoints doesn't throw exceptions it
440 # returns a list of failed 'results' instead. Throw these so we can
441 # catch them the way we expect
442 for r in result:
443 try:
444 raise botocore.exceptions.ClientError(r, "delete_vpc_endpoints")
445 except is_boto3_error_code("InvalidVpcEndpoint.NotFound"):
446 continue
447
448 except AnsibleEC2Error as e:
449 module.fail_json_aws(e, "Failed to delete VPC endpoint")
450 return changed, result
451
452
453 def main() -> None:
454 argument_spec = dict(
455 vpc_id=dict(),
456 vpc_endpoint_type=dict(default="Gateway", choices=["Interface", "Gateway", "GatewayLoadBalancer"]),
457 vpc_endpoint_security_groups=dict(type="list", elements="str"),
458 vpc_endpoint_subnets=dict(type="list", elements="str"),
459 service=dict(),
460 policy=dict(type="json"),
461 state=dict(default="present", choices=["present", "absent"]),
462 wait=dict(type="bool", default=False),
463 wait_timeout=dict(type="int", default=320, required=False),
464 route_table_ids=dict(type="list", elements="str"),
465 vpc_endpoint_id=dict(),
466 client_token=dict(no_log=False),
467 tags=dict(type="dict", aliases=["resource_tags"]),
468 purge_tags=dict(type="bool", default=True),
469 )
470 module = AnsibleAWSModule(
471 argument_spec=argument_spec,
472 supports_check_mode=True,
473 required_if=[
474 ["state", "present", ["vpc_id", "service"]],
475 ["state", "absent", ["vpc_endpoint_id"]],
476 ],
477 )
478
479 # Validate Requirements
480 state = module.params.get("state")
481
482 if module.params.get("vpc_endpoint_type"):
483 if module.params.get("vpc_endpoint_type") == "Gateway":
484 if module.params.get("vpc_endpoint_subnets") or module.params.get("vpc_endpoint_security_groups"):
485 module.fail_json(
486 msg=(
487 "Parameter vpc_endpoint_subnets and/or vpc_endpoint_security_groups can't be used with Gateway"
488 " endpoint type"
489 )
490 )
491
492 if module.params.get("vpc_endpoint_type") == "GatewayLoadBalancer":
493 if module.params.get("vpc_endpoint_security_groups"):
494 module.fail_json(
495 msg="Parameter vpc_endpoint_security_groups can't be used with GatewayLoadBalancer endpoint type"
496 )
497
498 if module.params.get("vpc_endpoint_type") == "Interface":
499 if module.params.get("vpc_endpoint_subnets") and not module.params.get("vpc_endpoint_security_groups"):
500 module.fail_json(
501 msg=(
502 "Parameter vpc_endpoint_security_groups must be set when endpoint type is Interface and"
503 " vpc_endpoint_subnets is defined"
504 )
505 )
506 if not module.params.get("vpc_endpoint_subnets") and module.params.get("vpc_endpoint_security_groups"):
507 module.fail_json(
508 msg=(
509 "Parameter vpc_endpoint_subnets must be set when endpoint type is Interface and"
510 " vpc_endpoint_security_groups is defined"
511 )
512 )
513
514 try:
515 ec2 = module.client("ec2")
516 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
517 module.fail_json_aws(e, msg="Failed to connect to AWS")
518
519 try:
520 # Ensure resource is present
521 if state == "present":
522 (changed, results) = setup_creation(ec2, module)
523 else:
524 (changed, results) = setup_removal(ec2, module)
525 except AnsibleEC2Error as e:
526 module.fail_json_aws_error(e)
527
528 module.exit_json(changed=changed, result=results)
529
530
531 if __name__ == "__main__":
532 main()