| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# This code is part of Ansible, but is an independent component. |
| 4 |
# This particular file snippet, and this file snippet only, is BSD licensed. |
| 5 |
# Modules you write using this snippet, which is embedded dynamically by Ansible |
| 6 |
# still belong to the author of the module, and may assign their own license |
| 7 |
# to the complete work. |
| 8 |
# |
| 9 |
# Copyright (c), Michael DeHaan <[email protected]>, 2012-2013 |
| 10 |
# All rights reserved. |
| 11 |
# |
| 12 |
# Redistribution and use in source and binary forms, with or without modification, |
| 13 |
# are permitted provided that the following conditions are met: |
| 14 |
# |
| 15 |
# * Redistributions of source code must retain the above copyright |
| 16 |
# notice, this list of conditions and the following disclaimer. |
| 17 |
# * Redistributions in binary form must reproduce the above copyright notice, |
| 18 |
# this list of conditions and the following disclaimer in the documentation |
| 19 |
# and/or other materials provided with the distribution. |
| 20 |
# |
| 21 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 22 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 23 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 24 |
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 25 |
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 26 |
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 27 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 28 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE |
| 29 |
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 30 |
|
| 31 |
from copy import deepcopy |
| 32 |
from typing import Any |
| 33 |
from typing import Callable |
| 34 |
from typing import Dict |
| 35 |
from typing import List |
| 36 |
from typing import Mapping |
| 37 |
from typing import Optional |
| 38 |
from typing import Sequence |
| 39 |
from typing import Union |
| 40 |
|
| 41 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 42 |
|
| 43 |
from .botocore import normalize_boto3_result |
| 44 |
from .tagging import boto3_tag_list_to_ansible_dict |
| 45 |
|
| 46 |
BotoResource = Union[None, Mapping[str, Any]] |
| 47 |
BotoResourceList = Union[None, Sequence[Mapping[str, Any]]] |
| 48 |
AnsibleAWSResource = Union[None, Mapping[str, Any]] |
| 49 |
AnsibleAWSResourceList = Union[None, Sequence[Mapping[str, Any]]] |
| 50 |
|
| 51 |
|
| 52 |
def ansible_dict_to_boto3_filter_list(filters_dict): |
| 53 |
"""Convert an Ansible dict of filters to list of dicts that boto3 can use |
| 54 |
Args: |
| 55 |
filters_dict (dict): Dict of AWS filters. |
| 56 |
Basic Usage: |
| 57 |
>>> filters = {'some-aws-id': 'i-01234567'} |
| 58 |
>>> ansible_dict_to_boto3_filter_list(filters) |
| 59 |
{ |
| 60 |
'some-aws-id': 'i-01234567' |
| 61 |
} |
| 62 |
Returns: |
| 63 |
List: List of AWS filters and their values |
| 64 |
[ |
| 65 |
{ |
| 66 |
'Name': 'some-aws-id', |
| 67 |
'Values': [ |
| 68 |
'i-01234567', |
| 69 |
] |
| 70 |
} |
| 71 |
] |
| 72 |
""" |
| 73 |
|
| 74 |
filters_list = [] |
| 75 |
for k, v in filters_dict.items(): |
| 76 |
filter_dict = {"Name": k} |
| 77 |
if isinstance(v, bool): |
| 78 |
filter_dict["Values"] = [str(v).lower()] |
| 79 |
elif isinstance(v, int): |
| 80 |
filter_dict["Values"] = [str(v)] |
| 81 |
elif isinstance(v, str): |
| 82 |
filter_dict["Values"] = [v] |
| 83 |
else: |
| 84 |
filter_dict["Values"] = v |
| 85 |
|
| 86 |
filters_list.append(filter_dict) |
| 87 |
|
| 88 |
return filters_list |
| 89 |
|
| 90 |
|
| 91 |
def map_complex_type(complex_type, type_map): |
| 92 |
""" |
| 93 |
Allows to cast elements within a dictionary to a specific type |
| 94 |
Example of usage: |
| 95 |
|
| 96 |
DEPLOYMENT_CONFIGURATION_TYPE_MAP = { |
| 97 |
'maximum_percent': 'int', |
| 98 |
'minimum_healthy_percent': 'int' |
| 99 |
} |
| 100 |
|
| 101 |
deployment_configuration = map_complex_type(module.params['deployment_configuration'], |
| 102 |
DEPLOYMENT_CONFIGURATION_TYPE_MAP) |
| 103 |
|
| 104 |
This ensures all keys within the root element are casted and valid integers |
| 105 |
""" |
| 106 |
|
| 107 |
if complex_type is None: |
| 108 |
return |
| 109 |
new_type = type(complex_type)() |
| 110 |
if isinstance(complex_type, dict): |
| 111 |
for key in complex_type: |
| 112 |
if key in type_map: |
| 113 |
if isinstance(type_map[key], list): |
| 114 |
new_type[key] = map_complex_type(complex_type[key], type_map[key][0]) |
| 115 |
else: |
| 116 |
new_type[key] = map_complex_type(complex_type[key], type_map[key]) |
| 117 |
else: |
| 118 |
new_type[key] = complex_type[key] |
| 119 |
elif isinstance(complex_type, list): |
| 120 |
for i in range(len(complex_type)): |
| 121 |
new_type.append(map_complex_type(complex_type[i], type_map)) |
| 122 |
elif type_map: |
| 123 |
return globals()["__builtins__"][type_map](complex_type) |
| 124 |
return new_type |
| 125 |
|
| 126 |
|
| 127 |
def scrub_none_parameters(parameters, descend_into_lists=True): |
| 128 |
""" |
| 129 |
Iterate over a dictionary removing any keys that have a None value |
| 130 |
|
| 131 |
Reference: https://github.com/ansible-collections/community.aws/issues/251 |
| 132 |
Credit: https://medium.com/better-programming/how-to-remove-null-none-values-from-a-dictionary-in-python-1bedf1aab5e4 |
| 133 |
|
| 134 |
:param descend_into_lists: whether or not to descend in to lists to continue to remove None values |
| 135 |
:param parameters: parameter dict |
| 136 |
:return: parameter dict with all keys = None removed |
| 137 |
""" |
| 138 |
|
| 139 |
clean_parameters = {} |
| 140 |
|
| 141 |
for k, v in parameters.items(): |
| 142 |
if isinstance(v, dict): |
| 143 |
clean_parameters[k] = scrub_none_parameters(v, descend_into_lists=descend_into_lists) |
| 144 |
elif descend_into_lists and isinstance(v, list): |
| 145 |
clean_parameters[k] = [ |
| 146 |
scrub_none_parameters(vv, descend_into_lists=descend_into_lists) if isinstance(vv, dict) else vv |
| 147 |
for vv in v |
| 148 |
] |
| 149 |
elif v is not None: |
| 150 |
clean_parameters[k] = v |
| 151 |
|
| 152 |
return clean_parameters |
| 153 |
|
| 154 |
|
| 155 |
def _perform_nested_transforms( |
| 156 |
resource: Mapping[str, Any], |
| 157 |
nested_transforms: Optional[Mapping[str, Callable]], |
| 158 |
) -> Mapping[str, Any]: |
| 159 |
if not nested_transforms: |
| 160 |
return resource |
| 161 |
|
| 162 |
for k, transform in nested_transforms.items(): |
| 163 |
if k in resource: |
| 164 |
resource[k] = transform(resource[k]) |
| 165 |
|
| 166 |
return resource |
| 167 |
|
| 168 |
|
| 169 |
def boto3_resource_to_ansible_dict( |
| 170 |
resource: BotoResource, |
| 171 |
transform_tags: bool = True, |
| 172 |
force_tags: bool = True, |
| 173 |
normalize: bool = True, |
| 174 |
ignore_list: Optional[Sequence[str]] = None, |
| 175 |
nested_transforms: Optional[Mapping[str, Callable]] = None, |
| 176 |
) -> AnsibleAWSResource: |
| 177 |
""" |
| 178 |
Transforms boto3-style (CamelCase) resource to the ansible-style (snake_case). |
| 179 |
|
| 180 |
:param resource: a dictionary representing the resource |
| 181 |
:param transform_tags: whether or not to perform "tag list" to "dictionary" conversion on the "Tags" key |
| 182 |
:param normalize: whether resources should be passed through .botocore.normalize_boto3_result |
| 183 |
:param ignore_list: a list of keys, the contents of which should not be transformed |
| 184 |
:param nested_transforms: a mapping of keys to Callable, the Callable will only be passed the value for the key |
| 185 |
in the resource dictionary |
| 186 |
:return: dictionary representing the transformed resource |
| 187 |
""" |
| 188 |
if not resource: |
| 189 |
return resource |
| 190 |
ignore_list = ignore_list or [] |
| 191 |
nested_transforms = nested_transforms or {} |
| 192 |
|
| 193 |
transformed_resource = deepcopy(resource) |
| 194 |
if normalize: |
| 195 |
transformed_resource = normalize_boto3_result(transformed_resource) |
| 196 |
transformed_resource = _perform_nested_transforms(transformed_resource, nested_transforms) |
| 197 |
ignore_list = [*ignore_list, *nested_transforms] |
| 198 |
camel_resource = camel_dict_to_snake_dict(transformed_resource, ignore_list=ignore_list) |
| 199 |
if transform_tags and "Tags" in resource: |
| 200 |
camel_resource["tags"] = boto3_tag_list_to_ansible_dict(resource["Tags"]) |
| 201 |
if force_tags and "Tags" not in resource: |
| 202 |
camel_resource["tags"] = {} |
| 203 |
|
| 204 |
return camel_resource |
| 205 |
|
| 206 |
|
| 207 |
def boto3_resource_list_to_ansible_dict( |
| 208 |
resource_list: BotoResourceList, |
| 209 |
transform_tags: bool = True, |
| 210 |
force_tags: bool = True, |
| 211 |
normalize: bool = True, |
| 212 |
ignore_list: Optional[Sequence[str]] = None, |
| 213 |
nested_transforms: Optional[Mapping[str, Callable]] = None, |
| 214 |
) -> AnsibleAWSResourceList: |
| 215 |
""" |
| 216 |
Transforms a list of boto3-style (CamelCase) resources to the ansible-style (snake_case). |
| 217 |
|
| 218 |
:param resource_list: a list of dictionaries representing the resources |
| 219 |
:param transform_tags: whether or not to perform "tag list" to "dictionary" conversion on the "Tags" key |
| 220 |
:param normalize: whether resources should be passed through .botocore.normalize_boto3_result() |
| 221 |
:param ignore_list: a list of keys, the contents of which should not be transformed |
| 222 |
:param nested_transforms: a mapping of keys to Callable, the Callable will only be passed the value for the key |
| 223 |
in the resource dictionary |
| 224 |
:return: list of dictionaries representing the transformed resources |
| 225 |
""" |
| 226 |
if not resource_list: |
| 227 |
return resource_list |
| 228 |
return [ |
| 229 |
boto3_resource_to_ansible_dict(resource, transform_tags, force_tags, normalize, ignore_list, nested_transforms) |
| 230 |
for resource in resource_list |
| 231 |
] |
| 232 |
|
| 233 |
|
| 234 |
def sanitize_filters_to_boto3_filter_list( |
| 235 |
filters: Dict[str, Any], ignore_keys: Optional[List[str]] = None |
| 236 |
) -> Dict[str, Any]: |
| 237 |
""" |
| 238 |
Replace filter key underscores with dashes, for compatibility and transform ansible dict |
| 239 |
into boto3 filter list. |
| 240 |
|
| 241 |
:param filters: Ansible module params filters. |
| 242 |
:param ignore_keys: A list of keys to ignore. |
| 243 |
:return: Sanitized filters |
| 244 |
""" |
| 245 |
sanitized_filters = deepcopy(filters) |
| 246 |
for k, v in filters.items(): |
| 247 |
if ignore_keys and any((k.startswith(x) for x in ignore_keys)): |
| 248 |
continue |
| 249 |
if "_" in k: |
| 250 |
sanitized_filters[k.replace("_", "-")] = v |
| 251 |
del sanitized_filters[k] |
| 252 |
return ansible_dict_to_boto3_filter_list(sanitized_filters) |