| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright (c) 2017 Willem van Ketwich |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
# Author: |
| 7 |
# - Willem van Ketwich <[email protected]> |
| 8 |
# |
| 9 |
# Common functionality to be used by the modules: |
| 10 |
# - cloudfront_distribution |
| 11 |
# - cloudfront_invalidation |
| 12 |
# - cloudfront_origin_access_identity |
| 13 |
|
| 14 |
""" |
| 15 |
Common cloudfront facts shared between modules |
| 16 |
""" |
| 17 |
|
| 18 |
from functools import partial |
| 19 |
|
| 20 |
try: |
| 21 |
import botocore |
| 22 |
except ImportError: |
| 23 |
pass |
| 24 |
|
| 25 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 26 |
|
| 27 |
from .retries import AWSRetry |
| 28 |
from .tagging import boto3_tag_list_to_ansible_dict |
| 29 |
|
| 30 |
|
| 31 |
class CloudFrontFactsServiceManagerFailure(Exception): |
| 32 |
pass |
| 33 |
|
| 34 |
|
| 35 |
def cloudfront_facts_keyed_list_helper(list_to_key): |
| 36 |
result = dict() |
| 37 |
for item in list_to_key: |
| 38 |
distribution_id = item["Id"] |
| 39 |
if "Items" in item["Aliases"]: |
| 40 |
result.update({alias: item for alias in item["Aliases"]["Items"]}) |
| 41 |
result.update({distribution_id: item}) |
| 42 |
return result |
| 43 |
|
| 44 |
|
| 45 |
@AWSRetry.jittered_backoff() |
| 46 |
def _cloudfront_paginate_build_full_result(client, client_method, **kwargs): |
| 47 |
paginator = client.get_paginator(client_method) |
| 48 |
return paginator.paginate(**kwargs).build_full_result() |
| 49 |
|
| 50 |
|
| 51 |
class CloudFrontFactsServiceManager: |
| 52 |
"""Handles CloudFront Facts Services""" |
| 53 |
|
| 54 |
CLOUDFRONT_CLIENT_API_MAPPING = { |
| 55 |
"get_distribution": { |
| 56 |
"error": "Error describing distribution", |
| 57 |
}, |
| 58 |
"get_distribution_config": { |
| 59 |
"error": "Error describing distribution configuration", |
| 60 |
}, |
| 61 |
"get_origin_access_identity": { |
| 62 |
"error": "Error describing origin access identity", |
| 63 |
"client_api": "get_cloud_front_origin_access_identity", |
| 64 |
}, |
| 65 |
"get_origin_access_identity_config": { |
| 66 |
"error": "Error describing origin access identity configuration", |
| 67 |
"client_api": "get_cloud_front_origin_access_identity_config", |
| 68 |
}, |
| 69 |
"get_streaming_distribution": { |
| 70 |
"error": "Error describing streaming distribution", |
| 71 |
}, |
| 72 |
"get_streaming_distribution_config": { |
| 73 |
"error": "Error describing streaming distribution", |
| 74 |
}, |
| 75 |
"get_invalidation": { |
| 76 |
"error": "Error describing invalidation", |
| 77 |
}, |
| 78 |
"list_distributions_by_web_acl_id": { |
| 79 |
"error": "Error listing distributions by web acl id", |
| 80 |
"post_process": lambda x: cloudfront_facts_keyed_list_helper( |
| 81 |
x.get("DistributionList", {}).get("Items", []) |
| 82 |
), |
| 83 |
}, |
| 84 |
} |
| 85 |
|
| 86 |
CLOUDFRONT_CLIENT_PAGINATE_API_MAPPING = { |
| 87 |
"list_origin_access_identities": { |
| 88 |
"error": "Error listing cloud front origin access identities", |
| 89 |
"client_api": "list_cloud_front_origin_access_identities", |
| 90 |
"key": "CloudFrontOriginAccessIdentityList", |
| 91 |
}, |
| 92 |
"list_distributions": { |
| 93 |
"error": "Error listing distributions", |
| 94 |
"key": "DistributionList", |
| 95 |
"keyed": True, |
| 96 |
}, |
| 97 |
"list_invalidations": {"error": "Error listing invalidations", "key": "InvalidationList"}, |
| 98 |
"list_streaming_distributions": { |
| 99 |
"error": "Error listing streaming distributions", |
| 100 |
"key": "StreamingDistributionList", |
| 101 |
"keyed": True, |
| 102 |
}, |
| 103 |
} |
| 104 |
|
| 105 |
def __init__(self, module): |
| 106 |
self.module = module |
| 107 |
self.client = module.client("cloudfront", retry_decorator=AWSRetry.jittered_backoff()) |
| 108 |
|
| 109 |
def describe_cloudfront_property(self, client_method, error, post_process, **kwargs): |
| 110 |
fail_if_error = kwargs.pop("fail_if_error", True) |
| 111 |
try: |
| 112 |
method = getattr(self.client, client_method) |
| 113 |
api_kwargs = snake_dict_to_camel_dict(kwargs, capitalize_first=True) |
| 114 |
result = method(aws_retry=True, **api_kwargs) |
| 115 |
result.pop("ResponseMetadata", None) |
| 116 |
if post_process: |
| 117 |
result = post_process(result) |
| 118 |
return result |
| 119 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 120 |
if not fail_if_error: |
| 121 |
raise |
| 122 |
self.module.fail_json_aws(e, msg=error) |
| 123 |
|
| 124 |
def paginate_list_cloudfront_property(self, client_method, key, default_keyed, error, **kwargs): |
| 125 |
fail_if_error = kwargs.pop("fail_if_error", True) |
| 126 |
try: |
| 127 |
keyed = kwargs.pop("keyed", default_keyed) |
| 128 |
api_kwargs = snake_dict_to_camel_dict(kwargs, capitalize_first=True) |
| 129 |
result = _cloudfront_paginate_build_full_result(self.client, client_method, **api_kwargs) |
| 130 |
items = result.get(key, {}).get("Items", []) |
| 131 |
if keyed: |
| 132 |
items = cloudfront_facts_keyed_list_helper(items) |
| 133 |
return items |
| 134 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 135 |
if not fail_if_error: |
| 136 |
raise |
| 137 |
self.module.fail_json_aws(e, msg=error) |
| 138 |
|
| 139 |
def __getattr__(self, name): |
| 140 |
if name in self.CLOUDFRONT_CLIENT_API_MAPPING: |
| 141 |
client_method = self.CLOUDFRONT_CLIENT_API_MAPPING[name].get("client_api", name) |
| 142 |
error = self.CLOUDFRONT_CLIENT_API_MAPPING[name].get("error", "") |
| 143 |
post_process = self.CLOUDFRONT_CLIENT_API_MAPPING[name].get("post_process") |
| 144 |
return partial(self.describe_cloudfront_property, client_method, error, post_process) |
| 145 |
|
| 146 |
elif name in self.CLOUDFRONT_CLIENT_PAGINATE_API_MAPPING: |
| 147 |
client_method = self.CLOUDFRONT_CLIENT_PAGINATE_API_MAPPING[name].get("client_api", name) |
| 148 |
error = self.CLOUDFRONT_CLIENT_PAGINATE_API_MAPPING[name].get("error", "") |
| 149 |
key = self.CLOUDFRONT_CLIENT_PAGINATE_API_MAPPING[name].get("key") |
| 150 |
keyed = self.CLOUDFRONT_CLIENT_PAGINATE_API_MAPPING[name].get("keyed", False) |
| 151 |
return partial(self.paginate_list_cloudfront_property, client_method, key, keyed, error) |
| 152 |
|
| 153 |
raise CloudFrontFactsServiceManagerFailure(f"Method {name} is not currently supported") |
| 154 |
|
| 155 |
def summary(self): |
| 156 |
summary_dict = {} |
| 157 |
summary_dict.update(self.summary_get_distribution_list(False)) |
| 158 |
summary_dict.update(self.summary_get_distribution_list(True)) |
| 159 |
summary_dict.update(self.summary_get_origin_access_identity_list()) |
| 160 |
return summary_dict |
| 161 |
|
| 162 |
def summary_get_origin_access_identity_list(self): |
| 163 |
try: |
| 164 |
origin_access_identities = [] |
| 165 |
for origin_access_identity in self.list_origin_access_identities(): |
| 166 |
oai_id = origin_access_identity["Id"] |
| 167 |
oai_full_response = self.get_origin_access_identity(id=oai_id) |
| 168 |
oai_summary = {"Id": oai_id, "ETag": oai_full_response["ETag"]} |
| 169 |
origin_access_identities.append(oai_summary) |
| 170 |
return {"origin_access_identities": origin_access_identities} |
| 171 |
except botocore.exceptions.ClientError as e: |
| 172 |
self.module.fail_json_aws(e, msg="Error generating summary of origin access identities") |
| 173 |
|
| 174 |
def list_resource_tags(self, resource_arn): |
| 175 |
return self.client.list_tags_for_resource(Resource=resource_arn, aws_retry=True) |
| 176 |
|
| 177 |
def summary_get_distribution_list(self, streaming=False): |
| 178 |
try: |
| 179 |
list_name = "streaming_distributions" if streaming else "distributions" |
| 180 |
key_list = ["Id", "ARN", "Status", "LastModifiedTime", "DomainName", "Comment", "PriceClass", "Enabled"] |
| 181 |
distribution_list = {list_name: []} |
| 182 |
distributions = ( |
| 183 |
self.list_streaming_distributions(keyed=False) if streaming else self.list_distributions(keyed=False) |
| 184 |
) |
| 185 |
for dist in distributions: |
| 186 |
temp_distribution = {k: dist[k] for k in key_list} |
| 187 |
temp_distribution["Aliases"] = list(dist["Aliases"].get("Items", [])) |
| 188 |
temp_distribution["ETag"] = self.get_etag_from_distribution_id(dist["Id"], streaming) |
| 189 |
if not streaming: |
| 190 |
temp_distribution["WebACLId"] = dist["WebACLId"] |
| 191 |
invalidation_ids = self.get_list_of_invalidation_ids_from_distribution_id(dist["Id"]) |
| 192 |
if invalidation_ids: |
| 193 |
temp_distribution["Invalidations"] = invalidation_ids |
| 194 |
resource_tags = self.list_resource_tags(dist["ARN"]) |
| 195 |
temp_distribution["Tags"] = boto3_tag_list_to_ansible_dict(resource_tags["Tags"].get("Items", [])) |
| 196 |
distribution_list[list_name].append(temp_distribution) |
| 197 |
return distribution_list |
| 198 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 199 |
self.module.fail_json_aws(e, msg="Error generating summary of distributions") |
| 200 |
|
| 201 |
def get_etag_from_distribution_id(self, distribution_id, streaming): |
| 202 |
distribution = {} |
| 203 |
if not streaming: |
| 204 |
distribution = self.get_distribution(id=distribution_id) |
| 205 |
else: |
| 206 |
distribution = self.get_streaming_distribution(id=distribution_id) |
| 207 |
return distribution["ETag"] |
| 208 |
|
| 209 |
def get_list_of_invalidation_ids_from_distribution_id(self, distribution_id): |
| 210 |
try: |
| 211 |
return list(map(lambda x: x["Id"], self.list_invalidations(distribution_id=distribution_id))) |
| 212 |
except botocore.exceptions.ClientError as e: |
| 213 |
self.module.fail_json_aws(e, msg="Error getting list of invalidation ids") |
| 214 |
|
| 215 |
def get_distribution_id_from_domain_name(self, domain_name): |
| 216 |
try: |
| 217 |
distribution_id = "" |
| 218 |
distributions = self.list_distributions(keyed=False) |
| 219 |
distributions += self.list_streaming_distributions(keyed=False) |
| 220 |
for dist in distributions: |
| 221 |
if any(str(alias).lower() == domain_name.lower() for alias in dist["Aliases"].get("Items", [])): |
| 222 |
distribution_id = dist["Id"] |
| 223 |
return distribution_id |
| 224 |
except botocore.exceptions.ClientError as e: |
| 225 |
self.module.fail_json_aws(e, msg="Error getting distribution id from domain name") |
| 226 |
|
| 227 |
def get_aliases_from_distribution_id(self, distribution_id): |
| 228 |
try: |
| 229 |
distribution = self.get_distribution(id=distribution_id) |
| 230 |
return distribution["Distribution"]["DistributionConfig"]["Aliases"].get("Items", []) |
| 231 |
except botocore.exceptions.ClientError as e: |
| 232 |
self.module.fail_json_aws(e, msg="Error getting list of aliases from distribution_id") |