| 1 |
# (c) 2013, Serge van Ginderachter <[email protected]> |
| 2 |
# (c) 2012-17 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
DOCUMENTATION = """ |
| 7 |
name: subelements |
| 8 |
author: Serge van Ginderachter (!UNKNOWN) <[email protected]> |
| 9 |
version_added: "1.4" |
| 10 |
short_description: traverse nested key from a list of dictionaries |
| 11 |
description: |
| 12 |
- Subelements walks a list of hashes (aka dictionaries) and then traverses a list with a given (nested sub-)key inside of those records. |
| 13 |
positional: _terms |
| 14 |
options: |
| 15 |
_terms: |
| 16 |
description: tuple of list of dictionaries and dictionary key to extract |
| 17 |
required: True |
| 18 |
skip_missing: |
| 19 |
default: False |
| 20 |
description: |
| 21 |
- Lookup accepts this flag from a dictionary as optional. See Example section for more information. |
| 22 |
- If set to V(True), the lookup plugin will skip the lists items that do not contain the given subkey. |
| 23 |
- If set to V(False), the plugin will yield an error and complain about the missing subkey. |
| 24 |
""" |
| 25 |
|
| 26 |
EXAMPLES = """ |
| 27 |
- name: show var structure as it is needed for example to make sense |
| 28 |
hosts: all |
| 29 |
vars: |
| 30 |
users: |
| 31 |
- name: alice |
| 32 |
authorized: |
| 33 |
- /tmp/alice/onekey.pub |
| 34 |
- /tmp/alice/twokey.pub |
| 35 |
mysql: |
| 36 |
password: mysql-password |
| 37 |
hosts: |
| 38 |
- "%" |
| 39 |
- "127.0.0.1" |
| 40 |
- "::1" |
| 41 |
- "localhost" |
| 42 |
privs: |
| 43 |
- "*.*:SELECT" |
| 44 |
- "DB1.*:ALL" |
| 45 |
groups: |
| 46 |
- wheel |
| 47 |
- name: bob |
| 48 |
authorized: |
| 49 |
- /tmp/bob/id_rsa.pub |
| 50 |
mysql: |
| 51 |
password: other-mysql-password |
| 52 |
hosts: |
| 53 |
- "db1" |
| 54 |
privs: |
| 55 |
- "*.*:SELECT" |
| 56 |
- "DB2.*:ALL" |
| 57 |
tasks: |
| 58 |
- name: Set authorized ssh key, extracting just that data from 'users' |
| 59 |
ansible.posix.authorized_key: |
| 60 |
user: "{{ item.0.name }}" |
| 61 |
key: "{{ lookup('file', item.1) }}" |
| 62 |
with_subelements: |
| 63 |
- "{{ users }}" |
| 64 |
- authorized |
| 65 |
|
| 66 |
- name: Setup MySQL users, given the mysql hosts and privs subkey lists |
| 67 |
community.mysql.mysql_user: |
| 68 |
name: "{{ item.0.name }}" |
| 69 |
password: "{{ item.0.mysql.password }}" |
| 70 |
host: "{{ item.1 }}" |
| 71 |
priv: "{{ item.0.mysql.privs | join('/') }}" |
| 72 |
with_subelements: |
| 73 |
- "{{ users }}" |
| 74 |
- mysql.hosts |
| 75 |
|
| 76 |
- name: list groups for users that have them, don't error if groups key is missing |
| 77 |
ansible.builtin.debug: var=item |
| 78 |
loop: "{{ q('ansible.builtin.subelements', users, 'groups', {'skip_missing': True}) }}" |
| 79 |
""" |
| 80 |
|
| 81 |
RETURN = """ |
| 82 |
_list: |
| 83 |
description: list of subelements extracted |
| 84 |
""" |
| 85 |
|
| 86 |
from ansible.errors import AnsibleError |
| 87 |
from ansible.module_utils.parsing.convert_bool import boolean |
| 88 |
from ansible.plugins.lookup import LookupBase |
| 89 |
|
| 90 |
|
| 91 |
FLAGS = ('skip_missing',) |
| 92 |
|
| 93 |
|
| 94 |
class LookupModule(LookupBase): |
| 95 |
|
| 96 |
def run(self, terms, variables=None, **kwargs): |
| 97 |
|
| 98 |
def _raise_terms_error(msg=""): |
| 99 |
raise AnsibleError( |
| 100 |
"subelements lookup expects a list of two or three items, " + msg) |
| 101 |
|
| 102 |
# check lookup terms - check number of terms |
| 103 |
if not isinstance(terms, list) or not 2 <= len(terms) <= 3: |
| 104 |
_raise_terms_error() |
| 105 |
|
| 106 |
# first term should be a list (or dict), second a string holding the subkey |
| 107 |
if not isinstance(terms[0], (list, dict)) or not isinstance(terms[1], str): |
| 108 |
_raise_terms_error("first a dict or a list, second a string pointing to the subkey") |
| 109 |
subelements = terms[1].split(".") |
| 110 |
|
| 111 |
if isinstance(terms[0], dict): # convert to list: |
| 112 |
if terms[0].get('skipped', False) is not False: |
| 113 |
# the registered result was completely skipped |
| 114 |
return [] |
| 115 |
elementlist = [] |
| 116 |
for key in terms[0]: |
| 117 |
elementlist.append(terms[0][key]) |
| 118 |
else: |
| 119 |
elementlist = terms[0] |
| 120 |
|
| 121 |
# check for optional flags in third term |
| 122 |
flags = {} |
| 123 |
if len(terms) == 3: |
| 124 |
flags = terms[2] |
| 125 |
if not isinstance(flags, dict) and not all(isinstance(key, str) and key in FLAGS for key in flags): |
| 126 |
_raise_terms_error("the optional third item must be a dict with flags %s" % FLAGS) |
| 127 |
|
| 128 |
# build_items |
| 129 |
ret = [] |
| 130 |
for item0 in elementlist: |
| 131 |
if not isinstance(item0, dict): |
| 132 |
raise AnsibleError("subelements lookup expects a dictionary, got '%s'" % item0) |
| 133 |
if item0.get('skipped', False) is not False: |
| 134 |
# this particular item is to be skipped |
| 135 |
continue |
| 136 |
|
| 137 |
skip_missing = boolean(flags.get('skip_missing', False), strict=False) |
| 138 |
subvalue = item0 |
| 139 |
lastsubkey = False |
| 140 |
sublist = [] |
| 141 |
for subkey in subelements: |
| 142 |
if subkey == subelements[-1]: |
| 143 |
lastsubkey = True |
| 144 |
if subkey not in subvalue: |
| 145 |
if skip_missing: |
| 146 |
continue |
| 147 |
else: |
| 148 |
raise AnsibleError("could not find '%s' key in iterated item '%s'" % (subkey, subvalue)) |
| 149 |
if not lastsubkey: |
| 150 |
if not isinstance(subvalue[subkey], dict): |
| 151 |
if skip_missing: |
| 152 |
continue |
| 153 |
else: |
| 154 |
raise AnsibleError("the key %s should point to a dictionary, got '%s'" % (subkey, subvalue[subkey])) |
| 155 |
else: |
| 156 |
subvalue = subvalue[subkey] |
| 157 |
else: # lastsubkey |
| 158 |
if not isinstance(subvalue[subkey], list): |
| 159 |
raise AnsibleError("the key %s should point to a list, got '%s'" % (subkey, subvalue[subkey])) |
| 160 |
else: |
| 161 |
sublist = subvalue.pop(subkey, []) |
| 162 |
for item1 in sublist: |
| 163 |
ret.append((item0, item1)) |
| 164 |
|
| 165 |
return ret |