| 1 |
# (c) 2015, Yannig Perre <yannig.perre(at)gmail.com> |
| 2 |
# (c) 2017 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: ini |
| 8 |
author: Yannig Perre (!UNKNOWN) <yannig.perre(at)gmail.com> |
| 9 |
version_added: "2.0" |
| 10 |
short_description: read data from an ini file |
| 11 |
description: |
| 12 |
- "The ini lookup reads the contents of a file in INI format C(key1=value1). |
| 13 |
This plugin retrieves the value on the right side after the equal sign C('=') of a given section C([section])." |
| 14 |
- "You can also read a property file which - in this case - does not contain section." |
| 15 |
positional: _terms |
| 16 |
options: |
| 17 |
_terms: |
| 18 |
description: The key(s) to look up. |
| 19 |
required: True |
| 20 |
type: |
| 21 |
description: Type of the file. 'properties' refers to the Java properties files. |
| 22 |
default: 'ini' |
| 23 |
choices: ['ini', 'properties'] |
| 24 |
file: |
| 25 |
description: Name of the file to load. |
| 26 |
default: 'ansible.ini' |
| 27 |
section: |
| 28 |
default: global |
| 29 |
description: Section where to lookup the key. |
| 30 |
re: |
| 31 |
default: False |
| 32 |
type: boolean |
| 33 |
description: Flag to indicate if the key supplied is a regexp. |
| 34 |
encoding: |
| 35 |
default: utf-8 |
| 36 |
description: Text encoding to use. |
| 37 |
default: |
| 38 |
description: Return value if the key is not in the ini file. |
| 39 |
default: '' |
| 40 |
case_sensitive: |
| 41 |
description: |
| 42 |
Whether key names read from O(file) should be case sensitive. This prevents |
| 43 |
duplicate key errors if keys only differ in case. |
| 44 |
default: False |
| 45 |
version_added: '2.12' |
| 46 |
allow_no_value: |
| 47 |
description: |
| 48 |
- Read an ini file which contains key without value and without '=' symbol. |
| 49 |
type: bool |
| 50 |
default: False |
| 51 |
aliases: ['allow_none'] |
| 52 |
version_added: '2.12' |
| 53 |
interpolation: |
| 54 |
description: |
| 55 |
Allows for interpolation of values, see https://docs.python.org/3/library/configparser.html#configparser.BasicInterpolation |
| 56 |
type: bool |
| 57 |
default: True |
| 58 |
version_added: '2.18' |
| 59 |
seealso: |
| 60 |
- ref: playbook_task_paths |
| 61 |
description: Search paths used for relative files. |
| 62 |
- module: community.general.ini_file |
| 63 |
- plugin: community.general.from_ini |
| 64 |
plugin_type: filter |
| 65 |
- plugin: community.general.to_ini |
| 66 |
plugin_type: filter |
| 67 |
""" |
| 68 |
|
| 69 |
EXAMPLES = """ |
| 70 |
- ansible.builtin.debug: msg="User in integration is {{ lookup('ansible.builtin.ini', 'user', section='integration', file='users.ini') }}" |
| 71 |
|
| 72 |
- ansible.builtin.debug: msg="User in production is {{ lookup('ansible.builtin.ini', 'user', section='production', file='users.ini') }}" |
| 73 |
|
| 74 |
- ansible.builtin.debug: msg="user.name is {{ lookup('ansible.builtin.ini', 'user.name', type='properties', file='user.properties') }}" |
| 75 |
|
| 76 |
- ansible.builtin.debug: |
| 77 |
msg: "{{ item }}" |
| 78 |
loop: "{{ q('ansible.builtin.ini', '.*', section='section1', file='test.ini', re=True) }}" |
| 79 |
|
| 80 |
- name: Read an ini file with allow_no_value |
| 81 |
ansible.builtin.debug: |
| 82 |
msg: "{{ lookup('ansible.builtin.ini', 'user', file='mysql.ini', section='mysqld', allow_no_value=True) }}" |
| 83 |
""" |
| 84 |
|
| 85 |
RETURN = """ |
| 86 |
_raw: |
| 87 |
description: |
| 88 |
- value(s) of the key(s) in the ini file |
| 89 |
type: list |
| 90 |
elements: str |
| 91 |
""" |
| 92 |
|
| 93 |
import configparser |
| 94 |
import os |
| 95 |
import re |
| 96 |
|
| 97 |
from io import StringIO |
| 98 |
from collections import defaultdict |
| 99 |
from collections.abc import MutableSequence |
| 100 |
|
| 101 |
from ansible.errors import AnsibleError |
| 102 |
from ansible.module_utils.common.text.converters import to_native |
| 103 |
from ansible.plugins.lookup import LookupBase |
| 104 |
|
| 105 |
|
| 106 |
def _parse_params(term, paramvals): |
| 107 |
"""Safely split parameter term to preserve spaces""" |
| 108 |
|
| 109 |
# TODO: deprecate this method |
| 110 |
valid_keys = paramvals.keys() |
| 111 |
params = defaultdict(lambda: '') |
| 112 |
|
| 113 |
# TODO: check kv_parser to see if it can handle spaces this same way |
| 114 |
keys = [] |
| 115 |
thiskey = 'key' # initialize for 'lookup item' |
| 116 |
for idp, phrase in enumerate(term.split()): |
| 117 |
|
| 118 |
# update current key if used |
| 119 |
if '=' in phrase: |
| 120 |
for k in valid_keys: |
| 121 |
if ('%s=' % k) in phrase: |
| 122 |
thiskey = k |
| 123 |
|
| 124 |
# if first term or key does not exist |
| 125 |
if idp == 0 or not params[thiskey]: |
| 126 |
params[thiskey] = phrase |
| 127 |
keys.append(thiskey) |
| 128 |
else: |
| 129 |
# append to existing key |
| 130 |
params[thiskey] += ' ' + phrase |
| 131 |
|
| 132 |
# return list of values |
| 133 |
return [params[x] for x in keys] |
| 134 |
|
| 135 |
|
| 136 |
class LookupModule(LookupBase): |
| 137 |
|
| 138 |
def get_value(self, key, section, dflt, is_regexp): |
| 139 |
# Retrieve all values from a section using a regexp |
| 140 |
if is_regexp: |
| 141 |
return [v for k, v in self.cp.items(section) if re.match(key, k)] |
| 142 |
value = None |
| 143 |
# Retrieve a single value |
| 144 |
try: |
| 145 |
value = self.cp.get(section, key) |
| 146 |
except configparser.NoOptionError: |
| 147 |
return dflt |
| 148 |
return value |
| 149 |
|
| 150 |
def run(self, terms, variables=None, **kwargs): |
| 151 |
|
| 152 |
self.set_options(var_options=variables, direct=kwargs) |
| 153 |
paramvals = self.get_options() |
| 154 |
|
| 155 |
self.cp = configparser.ConfigParser( |
| 156 |
allow_no_value=paramvals.get('allow_no_value', paramvals.get('allow_none')), |
| 157 |
interpolation=configparser.BasicInterpolation() if paramvals.get('interpolation') else None, |
| 158 |
) |
| 159 |
if paramvals['case_sensitive']: |
| 160 |
self.cp.optionxform = to_native |
| 161 |
|
| 162 |
ret = [] |
| 163 |
for term in terms: |
| 164 |
|
| 165 |
key = term |
| 166 |
# parameters specified? |
| 167 |
if '=' in term or ' ' in term.strip(): |
| 168 |
self._deprecate_inline_kv() |
| 169 |
params = _parse_params(term, paramvals) |
| 170 |
param = None |
| 171 |
try: |
| 172 |
updated_key = False |
| 173 |
updated_options = False |
| 174 |
for param in params: |
| 175 |
if '=' in param: |
| 176 |
name, value = param.split('=') |
| 177 |
if name not in paramvals: |
| 178 |
raise AnsibleError(f"{name!r} is not a valid option.") |
| 179 |
self.set_option(name, value) |
| 180 |
updated_options = True |
| 181 |
elif key == term: |
| 182 |
# only take first, this format never supported multiple keys inline |
| 183 |
key = param |
| 184 |
updated_key = True |
| 185 |
if updated_options: |
| 186 |
paramvals = self.get_options() |
| 187 |
except ValueError as ex: |
| 188 |
# bad params passed |
| 189 |
raise ValueError(f"Could not use {param!r} from {params!r}.") from ex |
| 190 |
if not updated_key: |
| 191 |
raise ValueError(f"No key to look up was provided as first term within string inline options: {term}") |
| 192 |
# only passed options in inline string |
| 193 |
|
| 194 |
# TODO: look to use cache to avoid redoing this for every term if they use same file |
| 195 |
# Retrieve file path |
| 196 |
path = self.find_file_in_search_path(variables, 'files', paramvals['file']) |
| 197 |
|
| 198 |
# Create StringIO later used to parse ini |
| 199 |
config = StringIO() |
| 200 |
# Special case for java properties |
| 201 |
if paramvals['type'] == "properties": |
| 202 |
config.write(u'[java_properties]\n') |
| 203 |
paramvals['section'] = 'java_properties' |
| 204 |
|
| 205 |
contents = self._loader.get_text_file_contents(path, encoding=paramvals['encoding']) |
| 206 |
config.write(contents) |
| 207 |
config.seek(0, os.SEEK_SET) |
| 208 |
|
| 209 |
try: |
| 210 |
self.cp.read_file(config) |
| 211 |
except configparser.DuplicateOptionError as ex: |
| 212 |
raise ValueError(f"Duplicate option in {paramvals['file']!r}.") from ex |
| 213 |
|
| 214 |
try: |
| 215 |
var = self.get_value(key, paramvals['section'], paramvals['default'], paramvals['re']) |
| 216 |
except configparser.NoSectionError: |
| 217 |
raise ValueError(f"No section {paramvals['section']!r} in {paramvals['file']!r}.") from None |
| 218 |
|
| 219 |
if var is not None: |
| 220 |
if isinstance(var, MutableSequence): |
| 221 |
for v in var: |
| 222 |
ret.append(v) |
| 223 |
else: |
| 224 |
ret.append(var) |
| 225 |
|
| 226 |
return ret |