| 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: api_gateway_domain |
| 10 |
short_description: Manage AWS API Gateway custom domains |
| 11 |
description: |
| 12 |
- Manages API Gateway custom domains for API GW Rest APIs. |
| 13 |
- AWS API Gateway custom domain setups use CloudFront behind the scenes. |
| 14 |
So you will get a CloudFront distribution as a result, configured to be aliased with your domain. |
| 15 |
- Prior to release 5.0.0 this module was called C(community.aws.aws_api_gateway_domain). |
| 16 |
The usage did not change. |
| 17 |
version_added: '3.3.0' |
| 18 |
author: |
| 19 |
- 'Stefan Horning (@stefanhorning)' |
| 20 |
options: |
| 21 |
domain_name: |
| 22 |
description: |
| 23 |
- Domain name you want to use for your API GW deployment. |
| 24 |
required: true |
| 25 |
type: str |
| 26 |
certificate_arn: |
| 27 |
description: |
| 28 |
- AWS Certificate Manger (ACM) TLS certificate ARN. |
| 29 |
type: str |
| 30 |
required: true |
| 31 |
security_policy: |
| 32 |
description: |
| 33 |
- Set allowed TLS versions through AWS defined policies. Currently only C(TLS_1_0) and C(TLS_1_2) are available. |
| 34 |
default: TLS_1_2 |
| 35 |
choices: ['TLS_1_0', 'TLS_1_2'] |
| 36 |
type: str |
| 37 |
endpoint_type: |
| 38 |
description: |
| 39 |
- API endpoint configuration for domain. Use EDGE for edge-optimized endpoint, or use C(REGIONAL) or C(PRIVATE). |
| 40 |
default: EDGE |
| 41 |
choices: ['EDGE', 'REGIONAL', 'PRIVATE'] |
| 42 |
type: str |
| 43 |
domain_mappings: |
| 44 |
description: |
| 45 |
- Map your domain base paths to your API GW REST APIs, that you previously created. Use provided ID of the API setup and the release stage. |
| 46 |
- "domain_mappings should be a list of dictionaries containing three keys: base_path, rest_api_id and stage." |
| 47 |
- "Example: I([{ base_path: v1, rest_api_id: abc123, stage: production }])" |
| 48 |
- if you want base path to be just I(/) omit the param completely or set it to empty string. |
| 49 |
required: true |
| 50 |
type: list |
| 51 |
elements: dict |
| 52 |
state: |
| 53 |
description: |
| 54 |
- Create or delete custom domain setup. |
| 55 |
default: present |
| 56 |
choices: [ 'present', 'absent' ] |
| 57 |
type: str |
| 58 |
notes: |
| 59 |
- Does not create a DNS entry on Route53, for that use the M(community.aws.route53) module. |
| 60 |
- Only supports TLS certificates from AWS ACM that can just be referenced by the ARN, while the AWS API still offers (deprecated) |
| 61 |
options to add own Certificates. |
| 62 |
extends_documentation_fragment: |
| 63 |
- amazon.aws.common.modules |
| 64 |
- amazon.aws.region.modules |
| 65 |
- amazon.aws.boto3 |
| 66 |
""" |
| 67 |
|
| 68 |
EXAMPLES = r""" |
| 69 |
- name: Setup endpoint for a custom domain for your API Gateway HTTP API |
| 70 |
community.aws.api_gateway_domain: |
| 71 |
domain_name: myapi.foobar.com |
| 72 |
certificate_arn: 'arn:aws:acm:us-east-1:1231123123:certificate/8bd89412-abc123-xxxxx' |
| 73 |
security_policy: TLS_1_2 |
| 74 |
endpoint_type: EDGE |
| 75 |
domain_mappings: |
| 76 |
- rest_api_id: abc123 |
| 77 |
stage: production |
| 78 |
state: present |
| 79 |
register: api_gw_domain_result |
| 80 |
|
| 81 |
- name: Create a DNS record for your custom domain on route 53 (using route53 module) |
| 82 |
community.aws.route53: |
| 83 |
record: myapi.foobar.com |
| 84 |
value: "{{ api_gw_domain_result.response.domain.distribution_domain_name }}" |
| 85 |
type: A |
| 86 |
alias: true |
| 87 |
zone: foobar.com |
| 88 |
alias_hosted_zone_id: "{{ api_gw_domain_result.response.domain.distribution_hosted_zone_id }}" |
| 89 |
command: create |
| 90 |
""" |
| 91 |
|
| 92 |
RETURN = r""" |
| 93 |
response: |
| 94 |
description: The data returned by create_domain_name (or update and delete) and create_base_path_mapping methods by boto3. |
| 95 |
returned: success |
| 96 |
type: dict |
| 97 |
sample: |
| 98 |
domain: |
| 99 |
{ |
| 100 |
domain_name: mydomain.com, |
| 101 |
certificate_arn: 'arn:aws:acm:xxxxxx', |
| 102 |
distribution_domain_name: xxxx.cloudfront.net, |
| 103 |
distribution_hosted_zone_id: ABC123123, |
| 104 |
endpoint_configuration: { types: ['EDGE'] }, |
| 105 |
domain_name_status: 'AVAILABLE', |
| 106 |
security_policy: TLS_1_2, |
| 107 |
tags: {} |
| 108 |
} |
| 109 |
path_mappings: [ |
| 110 |
{ base_path: '(empty)', rest_api_id: 'abcd123', stage: 'production' } |
| 111 |
] |
| 112 |
""" |
| 113 |
|
| 114 |
import copy |
| 115 |
|
| 116 |
try: |
| 117 |
from botocore.exceptions import BotoCoreError |
| 118 |
from botocore.exceptions import ClientError |
| 119 |
from botocore.exceptions import EndpointConnectionError |
| 120 |
except ImportError: |
| 121 |
pass # caught by imported AnsibleAWSModule |
| 122 |
|
| 123 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 124 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 125 |
|
| 126 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 127 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 128 |
|
| 129 |
from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule |
| 130 |
|
| 131 |
|
| 132 |
def get_domain(module, client): |
| 133 |
domain_name = module.params.get("domain_name") |
| 134 |
result = {} |
| 135 |
try: |
| 136 |
result["domain"] = get_domain_name(client, domain_name) |
| 137 |
result["path_mappings"] = get_domain_mappings(client, domain_name) |
| 138 |
except is_boto3_error_code("NotFoundException"): |
| 139 |
return None |
| 140 |
except (ClientError, BotoCoreError, EndpointConnectionError) as e: # pylint: disable=duplicate-except |
| 141 |
module.fail_json_aws(e, msg="getting API GW domain") |
| 142 |
return camel_dict_to_snake_dict(result) |
| 143 |
|
| 144 |
|
| 145 |
def create_domain(module, client): |
| 146 |
path_mappings = module.params.get("domain_mappings", []) |
| 147 |
domain_name = module.params.get("domain_name") |
| 148 |
result = {"domain": {}, "path_mappings": []} |
| 149 |
|
| 150 |
try: |
| 151 |
result["domain"] = create_domain_name( |
| 152 |
module, |
| 153 |
client, |
| 154 |
domain_name, |
| 155 |
module.params.get("certificate_arn"), |
| 156 |
module.params.get("endpoint_type"), |
| 157 |
module.params.get("security_policy"), |
| 158 |
) |
| 159 |
|
| 160 |
for mapping in path_mappings: |
| 161 |
base_path = mapping.get("base_path", "") |
| 162 |
rest_api_id = mapping.get("rest_api_id") |
| 163 |
stage = mapping.get("stage") |
| 164 |
if rest_api_id is None or stage is None: |
| 165 |
module.fail_json("Every domain mapping needs a rest_api_id and stage name") |
| 166 |
|
| 167 |
result["path_mappings"].append(add_domain_mapping(client, domain_name, base_path, rest_api_id, stage)) |
| 168 |
|
| 169 |
except (ClientError, BotoCoreError, EndpointConnectionError) as e: |
| 170 |
module.fail_json_aws(e, msg="creating API GW domain") |
| 171 |
return camel_dict_to_snake_dict(result) |
| 172 |
|
| 173 |
|
| 174 |
def update_domain(module, client, existing_domain): |
| 175 |
domain_name = module.params.get("domain_name") |
| 176 |
result = existing_domain |
| 177 |
result["updated"] = False |
| 178 |
|
| 179 |
domain = existing_domain.get("domain") |
| 180 |
# Compare only relevant set of domain arguments. |
| 181 |
# As get_domain_name gathers all kind of state information that can't be set anyways. |
| 182 |
# Also this module doesn't support custom TLS cert setup params as they are kind of deprecated already and would increase complexity. |
| 183 |
existing_domain_settings = { |
| 184 |
"certificate_arn": domain.get("certificate_arn"), |
| 185 |
"security_policy": domain.get("security_policy"), |
| 186 |
"endpoint_type": domain.get("endpoint_configuration").get("types")[0], |
| 187 |
} |
| 188 |
specified_domain_settings = { |
| 189 |
"certificate_arn": module.params.get("certificate_arn"), |
| 190 |
"security_policy": module.params.get("security_policy"), |
| 191 |
"endpoint_type": module.params.get("endpoint_type"), |
| 192 |
} |
| 193 |
|
| 194 |
if specified_domain_settings != existing_domain_settings: |
| 195 |
try: |
| 196 |
result["domain"] = update_domain_name( |
| 197 |
client, domain_name, **snake_dict_to_camel_dict(specified_domain_settings) |
| 198 |
) |
| 199 |
result["updated"] = True |
| 200 |
except (ClientError, BotoCoreError, EndpointConnectionError) as e: |
| 201 |
module.fail_json_aws(e, msg="updating API GW domain") |
| 202 |
|
| 203 |
existing_mappings = copy.deepcopy(existing_domain.get("path_mappings", [])) |
| 204 |
# Cleanout `base_path: "(none)"` elements from dicts as those won't match with specified mappings |
| 205 |
for mapping in existing_mappings: |
| 206 |
if mapping.get("base_path", "missing") == "(none)": |
| 207 |
mapping.pop("base_path") |
| 208 |
|
| 209 |
specified_mappings = copy.deepcopy(module.params.get("domain_mappings", [])) |
| 210 |
# Cleanout `base_path: ""` elements from dicts as those won't match with existing mappings |
| 211 |
for mapping in specified_mappings: |
| 212 |
if mapping.get("base_path", "missing") == "": |
| 213 |
mapping.pop("base_path") |
| 214 |
|
| 215 |
if specified_mappings != existing_mappings: |
| 216 |
try: |
| 217 |
# When lists missmatch delete all existing mappings before adding new ones as specified |
| 218 |
for mapping in existing_domain.get("path_mappings", []): |
| 219 |
delete_domain_mapping(client, domain_name, mapping["base_path"]) |
| 220 |
for mapping in module.params.get("domain_mappings", []): |
| 221 |
result["path_mappings"] = add_domain_mapping( |
| 222 |
client, domain_name, mapping.get("base_path", ""), mapping.get("rest_api_id"), mapping.get("stage") |
| 223 |
) |
| 224 |
result["updated"] = True |
| 225 |
except (ClientError, BotoCoreError, EndpointConnectionError) as e: |
| 226 |
module.fail_json_aws(e, msg="updating API GW domain mapping") |
| 227 |
|
| 228 |
return camel_dict_to_snake_dict(result) |
| 229 |
|
| 230 |
|
| 231 |
def delete_domain(module, client): |
| 232 |
domain_name = module.params.get("domain_name") |
| 233 |
try: |
| 234 |
result = delete_domain_name(client, domain_name) |
| 235 |
except (ClientError, BotoCoreError, EndpointConnectionError) as e: |
| 236 |
module.fail_json_aws(e, msg="deleting API GW domain") |
| 237 |
return camel_dict_to_snake_dict(result) |
| 238 |
|
| 239 |
|
| 240 |
retry_params = {"delay": 5, "backoff": 1.2} |
| 241 |
|
| 242 |
|
| 243 |
@AWSRetry.jittered_backoff(**retry_params) |
| 244 |
def get_domain_name(client, domain_name): |
| 245 |
return client.get_domain_name(domainName=domain_name) |
| 246 |
|
| 247 |
|
| 248 |
@AWSRetry.jittered_backoff(**retry_params) |
| 249 |
def get_domain_mappings(client, domain_name): |
| 250 |
return client.get_base_path_mappings(domainName=domain_name, limit=200).get("items", []) |
| 251 |
|
| 252 |
|
| 253 |
@AWSRetry.jittered_backoff(**retry_params) |
| 254 |
def create_domain_name(module, client, domain_name, certificate_arn, endpoint_type, security_policy): |
| 255 |
endpoint_configuration = {"types": [endpoint_type]} |
| 256 |
|
| 257 |
if endpoint_type == "EDGE": |
| 258 |
return client.create_domain_name( |
| 259 |
domainName=domain_name, |
| 260 |
certificateArn=certificate_arn, |
| 261 |
endpointConfiguration=endpoint_configuration, |
| 262 |
securityPolicy=security_policy, |
| 263 |
) |
| 264 |
else: |
| 265 |
# Use regionalCertificateArn for regional domain deploys |
| 266 |
return client.create_domain_name( |
| 267 |
domainName=domain_name, |
| 268 |
regionalCertificateArn=certificate_arn, |
| 269 |
endpointConfiguration=endpoint_configuration, |
| 270 |
securityPolicy=security_policy, |
| 271 |
) |
| 272 |
|
| 273 |
|
| 274 |
@AWSRetry.jittered_backoff(**retry_params) |
| 275 |
def add_domain_mapping(client, domain_name, base_path, rest_api_id, stage): |
| 276 |
return client.create_base_path_mapping( |
| 277 |
domainName=domain_name, basePath=base_path, restApiId=rest_api_id, stage=stage |
| 278 |
) |
| 279 |
|
| 280 |
|
| 281 |
@AWSRetry.jittered_backoff(**retry_params) |
| 282 |
def update_domain_name(client, domain_name, **kwargs): |
| 283 |
patch_operations = [] |
| 284 |
|
| 285 |
for key, value in kwargs.items(): |
| 286 |
path = "/" + key |
| 287 |
if key == "endpointType": |
| 288 |
continue |
| 289 |
patch_operations.append({"op": "replace", "path": path, "value": value}) |
| 290 |
|
| 291 |
return client.update_domain_name(domainName=domain_name, patchOperations=patch_operations) |
| 292 |
|
| 293 |
|
| 294 |
@AWSRetry.jittered_backoff(**retry_params) |
| 295 |
def delete_domain_name(client, domain_name): |
| 296 |
return client.delete_domain_name(domainName=domain_name) |
| 297 |
|
| 298 |
|
| 299 |
@AWSRetry.jittered_backoff(**retry_params) |
| 300 |
def delete_domain_mapping(client, domain_name, base_path): |
| 301 |
return client.delete_base_path_mapping(domainName=domain_name, basePath=base_path) |
| 302 |
|
| 303 |
|
| 304 |
def main(): |
| 305 |
argument_spec = dict( |
| 306 |
domain_name=dict(type="str", required=True), |
| 307 |
certificate_arn=dict(type="str", required=True), |
| 308 |
security_policy=dict(type="str", default="TLS_1_2", choices=["TLS_1_0", "TLS_1_2"]), |
| 309 |
endpoint_type=dict(type="str", default="EDGE", choices=["EDGE", "REGIONAL", "PRIVATE"]), |
| 310 |
domain_mappings=dict(type="list", required=True, elements="dict"), |
| 311 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 312 |
) |
| 313 |
|
| 314 |
module = AnsibleAWSModule( |
| 315 |
argument_spec=argument_spec, |
| 316 |
supports_check_mode=False, |
| 317 |
) |
| 318 |
|
| 319 |
client = module.client("apigateway") |
| 320 |
|
| 321 |
state = module.params.get("state") |
| 322 |
changed = False |
| 323 |
|
| 324 |
if state == "present": |
| 325 |
existing_domain = get_domain(module, client) |
| 326 |
if existing_domain is not None: |
| 327 |
result = update_domain(module, client, existing_domain) |
| 328 |
changed = result["updated"] |
| 329 |
else: |
| 330 |
result = create_domain(module, client) |
| 331 |
changed = True |
| 332 |
if state == "absent": |
| 333 |
result = delete_domain(module, client) |
| 334 |
changed = True |
| 335 |
|
| 336 |
exit_args = {"changed": changed} |
| 337 |
|
| 338 |
if result is not None: |
| 339 |
exit_args["response"] = result |
| 340 |
|
| 341 |
module.exit_json(**exit_args) |
| 342 |
|
| 343 |
|
| 344 |
if __name__ == "__main__": |
| 345 |
main() |