Debian Codegraph @

lib/ansible/plugins/lookup/lines.py

raw
1 # (c) 2012, Daniel Hokka Zakrisson <[email protected]>
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
5 from __future__ import annotations
6
7 DOCUMENTATION = """
8 name: lines
9 author: Daniel Hokka Zakrisson (!UNKNOWN) <[email protected]>
10 version_added: "0.9"
11 short_description: read lines from command
12 description:
13 - Run one or more commands and split the output into lines, returning them as a list
14 positional: _terms
15 options:
16 _terms:
17 description: command(s) to run
18 required: True
19 notes:
20 - The given commands are passed to a shell for execution, therefore all variables that are part of the commands and
21 come from a remote/untrusted source MUST be sanitized using the P(ansible.builtin.quote#filter) filter to avoid
22 shell injection vulnerabilities. See the example section.
23 - Like all lookups, this runs on the Ansible controller and is unaffected by other keywords such as 'become'.
24 If you need to use different permissions, you must change the command or run Ansible as another user.
25 - Alternatively, you can use a shell/command task that runs against localhost and registers the result.
26 - The directory of the play is used as the current working directory.
27 """
28
29 EXAMPLES = """
30 - name: We could read the file directly, but this shows output from command
31 ansible.builtin.debug: msg="{{ item }} is an output line from running cat on /etc/motd"
32 with_lines: cat /etc/motd
33
34 - name: Always use quote filter to make sure your variables are safe to use with shell
35 ansible.builtin.debug: msg="{{ item }} is an output line from running given command"
36 with_lines: "cat {{ file_name | quote }}"
37
38 - name: More useful example of looping over a command result
39 ansible.builtin.shell: "/usr/bin/frobnicate {{ item }}"
40 with_lines:
41 - "/usr/bin/frobnications_per_host --param {{ inventory_hostname }}"
42 """
43
44 RETURN = """
45 _list:
46 description:
47 - lines of stdout from command
48 type: list
49 elements: str
50 """
51
52 import subprocess
53 from ansible.errors import AnsibleError
54 from ansible.plugins.lookup import LookupBase
55 from ansible.module_utils.common.text.converters import to_text
56
57
58 class LookupModule(LookupBase):
59
60 def run(self, terms, variables=None, **kwargs):
61
62 ret = []
63 for term in terms:
64 p = subprocess.Popen(term, cwd=self._loader.get_basedir(), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
65 (stdout, stderr) = p.communicate()
66 if p.returncode == 0:
67 ret.extend([to_text(l) for l in stdout.splitlines()])
68 else:
69 raise AnsibleError("lookup_plugin.lines(%s) returned %d" % (term, p.returncode))
70 return ret