| 1 |
# Copyright (c) 2015-2021, Felix Fontein <[email protected]> |
| 2 |
# Copyright (c) 2018 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
name: dependent |
| 9 |
short_description: Composes a list with nested elements of other lists or dicts which can depend on previous loop variables |
| 10 |
author: Felix Fontein (@felixfontein) |
| 11 |
version_added: 3.1.0 |
| 12 |
description: |
| 13 |
- Takes the input lists and returns a list with elements that are lists, dictionaries, or template expressions which evaluate |
| 14 |
to lists or dicts, composed of the elements of the input evaluated lists and dictionaries. |
| 15 |
options: |
| 16 |
_terms: |
| 17 |
description: |
| 18 |
- A list where the elements are one-element dictionaries, mapping a name to a string, list, or dictionary. The name |
| 19 |
is the index that is used in the result object. The value is iterated over as described below. |
| 20 |
- If the value is a list, it is simply iterated over. |
| 21 |
- If the value is a dictionary, it is iterated over and returned as if they would be processed by the P(ansible.builtin.dict2items#filter) |
| 22 |
filter. |
| 23 |
- If the value is a string, it is evaluated as Jinja2 expressions which can access the previously chosen elements with |
| 24 |
C(item.<index_name>). The result must be a list or a dictionary. |
| 25 |
type: list |
| 26 |
elements: dict |
| 27 |
required: true |
| 28 |
""" |
| 29 |
|
| 30 |
EXAMPLES = r""" |
| 31 |
- name: Install/remove public keys for active admin users |
| 32 |
ansible.posix.authorized_key: |
| 33 |
user: "{{ item.admin.key }}" |
| 34 |
key: "{{ lookup('file', item.key.public_key) }}" |
| 35 |
state: "{{ 'present' if item.key.active else 'absent' }}" |
| 36 |
when: item.admin.value.active |
| 37 |
with_community.general.dependent: |
| 38 |
- admin: admin_user_data |
| 39 |
- key: admin_ssh_keys[item.admin.key] |
| 40 |
loop_control: |
| 41 |
# Makes the output readable, so that it doesn't contain the whole subdictionaries and lists |
| 42 |
label: "{{ [item.admin.key, 'active' if item.key.active else 'inactive', item.key.public_key] }}" |
| 43 |
vars: |
| 44 |
admin_user_data: |
| 45 |
admin1: |
| 46 |
name: Alice |
| 47 |
active: true |
| 48 |
admin2: |
| 49 |
name: Bob |
| 50 |
active: true |
| 51 |
admin_ssh_keys: |
| 52 |
admin1: |
| 53 |
- private_key: keys/private_key_admin1.pem |
| 54 |
public_key: keys/private_key_admin1.pub |
| 55 |
active: true |
| 56 |
admin2: |
| 57 |
- private_key: keys/private_key_admin2.pem |
| 58 |
public_key: keys/private_key_admin2.pub |
| 59 |
active: true |
| 60 |
- private_key: keys/private_key_admin2-old.pem |
| 61 |
public_key: keys/private_key_admin2-old.pub |
| 62 |
active: false |
| 63 |
|
| 64 |
- name: Update DNS records |
| 65 |
community.aws.route53: |
| 66 |
zone: "{{ item.zone.key }}" |
| 67 |
record: "{{ item.prefix.key ~ '.' if item.prefix.key else '' }}{{ item.zone.key }}" |
| 68 |
type: "{{ item.entry.key }}" |
| 69 |
ttl: "{{ item.entry.value.ttl | default(3600) }}" |
| 70 |
value: "{{ item.entry.value.value }}" |
| 71 |
state: "{{ 'absent' if (item.entry.value.absent | default(False)) else 'present' }}" |
| 72 |
overwrite: true |
| 73 |
loop_control: |
| 74 |
# Makes the output readable, so that it doesn't contain the whole subdictionaries and lists |
| 75 |
label: |- |
| 76 |
{{ [item.zone.key, item.prefix.key, item.entry.key, |
| 77 |
item.entry.value.ttl | default(3600), |
| 78 |
item.entry.value.absent | default(False), item.entry.value.value] }} |
| 79 |
with_community.general.dependent: |
| 80 |
- zone: dns_setup |
| 81 |
- prefix: item.zone.value |
| 82 |
- entry: item.prefix.value |
| 83 |
vars: |
| 84 |
dns_setup: |
| 85 |
example.com: |
| 86 |
'': |
| 87 |
A: |
| 88 |
value: |
| 89 |
- 1.2.3.4 |
| 90 |
AAAA: |
| 91 |
value: |
| 92 |
- "2a01:1:2:3::1" |
| 93 |
'test._domainkey': |
| 94 |
TXT: |
| 95 |
ttl: 300 |
| 96 |
value: |
| 97 |
- '"k=rsa; t=s; p=MIGfMA..."' |
| 98 |
example.org: |
| 99 |
'www': |
| 100 |
A: |
| 101 |
value: |
| 102 |
- 1.2.3.4 |
| 103 |
- 5.6.7.8 |
| 104 |
""" |
| 105 |
|
| 106 |
RETURN = r""" |
| 107 |
_list: |
| 108 |
description: |
| 109 |
- A list composed of dictionaries whose keys are the variable names from the input list. |
| 110 |
type: list |
| 111 |
elements: dict |
| 112 |
sample: |
| 113 |
- key1: a |
| 114 |
key2: test |
| 115 |
- key1: a |
| 116 |
key2: foo |
| 117 |
- key1: b |
| 118 |
key2: bar |
| 119 |
""" |
| 120 |
|
| 121 |
from collections.abc import Mapping, Sequence |
| 122 |
|
| 123 |
from ansible.errors import AnsibleLookupError |
| 124 |
from ansible.plugins.lookup import LookupBase |
| 125 |
from ansible.template import Templar |
| 126 |
|
| 127 |
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms |
| 128 |
|
| 129 |
try: |
| 130 |
from ansible.template import trust_as_template as _trust_as_template |
| 131 |
|
| 132 |
HAS_DATATAGGING = True |
| 133 |
except ImportError: |
| 134 |
HAS_DATATAGGING = False |
| 135 |
|
| 136 |
|
| 137 |
def _make_safe(value): |
| 138 |
if HAS_DATATAGGING and isinstance(value, str): |
| 139 |
return _trust_as_template(value) |
| 140 |
return value |
| 141 |
|
| 142 |
|
| 143 |
class LookupModule(LookupBase): |
| 144 |
def __evaluate(self, expression, templar, variables): |
| 145 |
"""Evaluate expression with templar. |
| 146 |
|
| 147 |
``expression`` is the expression to evaluate. |
| 148 |
``variables`` are the variables to use. |
| 149 |
""" |
| 150 |
templar.available_variables = variables or {} |
| 151 |
open_br = "{{" |
| 152 |
close_br = "}}" |
| 153 |
quoted_expression = f"{open_br}{expression}{close_br}" |
| 154 |
if hasattr(templar, "evaluate_expression"): |
| 155 |
# This is available since the Data Tagging PR has been merged |
| 156 |
return templar.evaluate_expression(_make_safe(expression)) |
| 157 |
return templar.template(quoted_expression) |
| 158 |
|
| 159 |
def __process(self, result, terms, index, current, templar, variables): |
| 160 |
"""Fills ``result`` list with evaluated items. |
| 161 |
|
| 162 |
``result`` is a list where the resulting items are placed. |
| 163 |
``terms`` is the parsed list of terms |
| 164 |
``index`` is the current index to be processed in the list. |
| 165 |
``current`` is a dictionary where the first ``index`` values are filled in. |
| 166 |
``variables`` are the variables currently available. |
| 167 |
""" |
| 168 |
# If we are done, add to result list: |
| 169 |
if index == len(terms): |
| 170 |
result.append(current.copy()) |
| 171 |
return |
| 172 |
|
| 173 |
key, expression, values = terms[index] |
| 174 |
|
| 175 |
if expression is not None: |
| 176 |
# Evaluate expression in current context |
| 177 |
vars = variables.copy() |
| 178 |
vars["item"] = current.copy() |
| 179 |
try: |
| 180 |
values = self.__evaluate(expression, templar, variables=vars) |
| 181 |
except Exception as e: |
| 182 |
raise AnsibleLookupError(f'Caught "{e}" while evaluating {key!r} with item == {current!r}') from e |
| 183 |
|
| 184 |
if isinstance(values, Mapping): |
| 185 |
for idx, val in sorted(values.items()): |
| 186 |
current[key] = dict(key=idx, value=val) |
| 187 |
self.__process(result, terms, index + 1, current, templar, variables) |
| 188 |
elif isinstance(values, Sequence): |
| 189 |
for elt in values: |
| 190 |
current[key] = elt |
| 191 |
self.__process(result, terms, index + 1, current, templar, variables) |
| 192 |
else: |
| 193 |
raise AnsibleLookupError( |
| 194 |
f"Did not obtain dictionary or list while evaluating {key!r} with item == {current!r}, but {type(values)}" |
| 195 |
) |
| 196 |
|
| 197 |
def run(self, terms, variables=None, **kwargs): |
| 198 |
"""Generate list.""" |
| 199 |
self.set_options(var_options=variables, direct=kwargs) |
| 200 |
check_for_wrong_terms(self, direct=kwargs) |
| 201 |
|
| 202 |
result = [] |
| 203 |
if len(terms) > 0: |
| 204 |
if HAS_DATATAGGING: |
| 205 |
templar = self._templar.copy_with_new_env(available_variables={}) |
| 206 |
else: |
| 207 |
templar = Templar(loader=self._templar._loader) |
| 208 |
data = [] |
| 209 |
vars_so_far = set() |
| 210 |
for index, term in enumerate(terms): |
| 211 |
if not isinstance(term, Mapping): |
| 212 |
raise AnsibleLookupError(f"Parameter {index} must be a dictionary, got {type(term)}") |
| 213 |
if len(term) != 1: |
| 214 |
raise AnsibleLookupError( |
| 215 |
f"Parameter {index} must be a one-element dictionary, got {len(term)} elements" |
| 216 |
) |
| 217 |
k, v = list(term.items())[0] |
| 218 |
if k in vars_so_far: |
| 219 |
raise AnsibleLookupError(f"The variable {k!r} appears more than once") |
| 220 |
vars_so_far.add(k) |
| 221 |
if isinstance(v, str): |
| 222 |
data.append((k, v, None)) |
| 223 |
elif isinstance(v, (Sequence, Mapping)): |
| 224 |
data.append((k, None, v)) |
| 225 |
else: |
| 226 |
raise AnsibleLookupError( |
| 227 |
f"Parameter {k!r} (index {index}) must have a value of type string, dictionary or list, got type {type(v)}" |
| 228 |
) |
| 229 |
self.__process(result, data, 0, {}, templar, variables) |
| 230 |
return result |