Debian Codegraph @

ansible_collections/community/general/plugins/modules/elasticsearch_plugin.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2015, Mathew Davies <[email protected]>
3 # Copyright (c) 2017, Sam Doran <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: elasticsearch_plugin
11 short_description: Manage Elasticsearch plugins
12 description:
13 - Manages Elasticsearch plugins.
14 author:
15 - Mathew Davies (@ThePixelDeveloper)
16 - Sam Doran (@samdoran)
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: none
24 options:
25 name:
26 description:
27 - Name of the plugin to install.
28 required: true
29 type: str
30 state:
31 description:
32 - Desired state of a plugin.
33 choices: ["present", "absent"]
34 default: present
35 type: str
36 src:
37 description:
38 - Optionally set the source location to retrieve the plugin from. This can be a C(file://) URL to install from a local
39 file, or a remote URL. If this is not set, the plugin location is just based on the name.
40 - The name parameter must match the descriptor in the plugin ZIP specified.
41 - Is only used if the state would change, which is solely checked based on the name parameter. If, for example, the
42 plugin is already installed, changing this has no effect.
43 - For ES 1.x use O(url).
44 type: str
45 url:
46 description:
47 - Set exact URL to download the plugin from (Only works for ES 1.x).
48 - For ES 2.x and higher, use src.
49 type: str
50 timeout:
51 description:
52 - 'Timeout setting: V(30s), V(1m), V(1h)...'
53 - Only valid for Elasticsearch < 5.0. This option is ignored for Elasticsearch > 5.0.
54 default: 1m
55 type: str
56 force:
57 description:
58 - Force batch mode when installing plugins. This is only necessary if a plugin requires additional permissions and console
59 detection fails.
60 default: false
61 type: bool
62 plugin_bin:
63 description:
64 - Location of the plugin binary. If this file is not found, the default plugin binaries are used.
65 type: path
66 plugin_dir:
67 description:
68 - Your configured plugin directory specified in Elasticsearch.
69 default: /usr/share/elasticsearch/plugins/
70 type: path
71 proxy_host:
72 description:
73 - Proxy host to use during plugin installation.
74 type: str
75 proxy_port:
76 description:
77 - Proxy port to use during plugin installation.
78 type: str
79 version:
80 description:
81 - Version of the plugin to be installed. If plugin exists with previous version, it is NOT updated.
82 type: str
83 """
84
85 EXAMPLES = r"""
86 - name: Install Elasticsearch Head plugin in Elasticsearch 2.x
87 community.general.elasticsearch_plugin:
88 name: mobz/elasticsearch-head
89 state: present
90
91 - name: Install a specific version of Elasticsearch Head in Elasticsearch 2.x
92 community.general.elasticsearch_plugin:
93 name: mobz/elasticsearch-head
94 version: 2.0.0
95
96 - name: Uninstall Elasticsearch head plugin in Elasticsearch 2.x
97 community.general.elasticsearch_plugin:
98 name: mobz/elasticsearch-head
99 state: absent
100
101 - name: Install a specific plugin in Elasticsearch >= 5.0
102 community.general.elasticsearch_plugin:
103 name: analysis-icu
104 state: present
105
106 - name: Install the ingest-geoip plugin with a forced installation
107 community.general.elasticsearch_plugin:
108 name: ingest-geoip
109 state: present
110 force: true
111 """
112
113 import os
114
115 from ansible.module_utils.basic import AnsibleModule
116
117 PACKAGE_STATE_MAP = dict(present="install", absent="remove")
118
119 PLUGIN_BIN_PATHS = tuple(["/usr/share/elasticsearch/bin/elasticsearch-plugin", "/usr/share/elasticsearch/bin/plugin"])
120
121
122 def parse_plugin_repo(string):
123 elements = string.split("/")
124
125 # We first consider the simplest form: pluginname
126 repo = elements[0]
127
128 # We consider the form: username/pluginname
129 if len(elements) > 1:
130 repo = elements[1]
131
132 # remove elasticsearch- prefix
133 # remove es- prefix
134 for string in ("elasticsearch-", "es-"):
135 if repo.startswith(string):
136 return repo[len(string) :]
137
138 return repo
139
140
141 def is_plugin_present(plugin_name, plugin_dir):
142 return os.path.isdir(os.path.join(plugin_dir, plugin_name))
143
144
145 def parse_error(string):
146 reason = "ERROR: "
147 try:
148 return string[string.index(reason) + len(reason) :].strip()
149 except ValueError:
150 return string
151
152
153 def install_plugin(module, plugin_bin, plugin_name, version, src, url, proxy_host, proxy_port, timeout, force):
154 cmd = [plugin_bin, PACKAGE_STATE_MAP["present"]]
155 is_old_command = os.path.basename(plugin_bin) == "plugin"
156
157 # Timeout and version are only valid for plugin, not elasticsearch-plugin
158 if is_old_command:
159 if timeout:
160 cmd.append("--timeout")
161 cmd.append(timeout)
162
163 if version:
164 plugin_name = f"{plugin_name}/{version}"
165 cmd[2] = plugin_name
166
167 if proxy_host and proxy_port:
168 java_opts = [
169 f"-Dhttp.proxyHost={proxy_host}",
170 f"-Dhttp.proxyPort={proxy_port}",
171 f"-Dhttps.proxyHost={proxy_host}",
172 f"-Dhttps.proxyPort={proxy_port}",
173 ]
174 module.run_command_environ_update = dict(
175 CLI_JAVA_OPTS=" ".join(java_opts), # Elasticsearch 8.x
176 ES_JAVA_OPTS=" ".join(java_opts),
177 ) # Older Elasticsearch versions
178
179 # Legacy ES 1.x
180 if url:
181 cmd.append("--url")
182 cmd.append(url)
183
184 if force:
185 cmd.append("--batch")
186 if src:
187 cmd.append(src)
188 else:
189 cmd.append(plugin_name)
190
191 if module.check_mode:
192 rc, out, err = 0, "check mode", ""
193 else:
194 rc, out, err = module.run_command(cmd)
195
196 if rc != 0:
197 reason = parse_error(out)
198 module.fail_json(msg=f"Installing plugin '{plugin_name}' failed: {reason}", err=err)
199
200 return True, cmd, out, err
201
202
203 def remove_plugin(module, plugin_bin, plugin_name):
204 cmd = [plugin_bin, PACKAGE_STATE_MAP["absent"], parse_plugin_repo(plugin_name)]
205
206 if module.check_mode:
207 rc, out, err = 0, "check mode", ""
208 else:
209 rc, out, err = module.run_command(cmd)
210
211 if rc != 0:
212 reason = parse_error(out)
213 module.fail_json(msg=f"Removing plugin '{plugin_name}' failed: {reason}", err=err)
214
215 return True, cmd, out, err
216
217
218 def get_plugin_bin(module, plugin_bin=None):
219 # Use the plugin_bin that was supplied first before trying other options
220 valid_plugin_bin = None
221 if plugin_bin and os.path.isfile(plugin_bin):
222 valid_plugin_bin = plugin_bin
223
224 else:
225 # Add the plugin_bin passed into the module to the top of the list of paths to test,
226 # testing for that binary name first before falling back to the default paths.
227 bin_paths = list(PLUGIN_BIN_PATHS)
228 if plugin_bin and plugin_bin not in bin_paths:
229 bin_paths.insert(0, plugin_bin)
230
231 # Get separate lists of dirs and binary names from the full paths to the
232 # plugin binaries.
233 plugin_dirs = list({os.path.dirname(x) for x in bin_paths})
234 plugin_bins = list({os.path.basename(x) for x in bin_paths})
235
236 # Check for the binary names in the default system paths as well as the path
237 # specified in the module arguments.
238 for bin_file in plugin_bins:
239 valid_plugin_bin = module.get_bin_path(bin_file, opt_dirs=plugin_dirs)
240 if valid_plugin_bin:
241 break
242
243 if not valid_plugin_bin:
244 module.fail_json(
245 msg=f"{plugin_bin} does not exist and no other valid plugin installers were found. Make sure Elasticsearch is installed."
246 )
247
248 return valid_plugin_bin
249
250
251 def main():
252 module = AnsibleModule(
253 argument_spec=dict(
254 name=dict(required=True),
255 state=dict(default="present", choices=list(PACKAGE_STATE_MAP.keys())),
256 src=dict(),
257 url=dict(),
258 timeout=dict(default="1m"),
259 force=dict(type="bool", default=False),
260 plugin_bin=dict(type="path"),
261 plugin_dir=dict(default="/usr/share/elasticsearch/plugins/", type="path"),
262 proxy_host=dict(),
263 proxy_port=dict(),
264 version=dict(),
265 ),
266 mutually_exclusive=[("src", "url")],
267 supports_check_mode=True,
268 )
269
270 name = module.params["name"]
271 state = module.params["state"]
272 url = module.params["url"]
273 src = module.params["src"]
274 timeout = module.params["timeout"]
275 force = module.params["force"]
276 plugin_bin = module.params["plugin_bin"]
277 plugin_dir = module.params["plugin_dir"]
278 proxy_host = module.params["proxy_host"]
279 proxy_port = module.params["proxy_port"]
280 version = module.params["version"]
281
282 # Search provided path and system paths for valid binary
283 plugin_bin = get_plugin_bin(module, plugin_bin)
284
285 repo = parse_plugin_repo(name)
286 present = is_plugin_present(repo, plugin_dir)
287
288 # skip if the state is correct
289 if (present and state == "present") or (state == "absent" and not present):
290 module.exit_json(changed=False, name=name, state=state)
291
292 if state == "present":
293 changed, cmd, out, err = install_plugin(
294 module, plugin_bin, name, version, src, url, proxy_host, proxy_port, timeout, force
295 )
296
297 elif state == "absent":
298 changed, cmd, out, err = remove_plugin(module, plugin_bin, name)
299
300 module.exit_json(changed=changed, cmd=cmd, name=name, state=state, url=url, timeout=timeout, stdout=out, stderr=err)
301
302
303 if __name__ == "__main__":
304 main()