Debian Codegraph @

lib/ansible/plugins/lookup/pipe.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 from __future__ import annotations
5
6 DOCUMENTATION = r"""
7 name: pipe
8 author: Daniel Hokka Zakrisson (!UNKNOWN) <[email protected]>
9 version_added: "0.9"
10 short_description: read output from a command
11 description:
12 - Run a command and return the output.
13 positional: _terms
14 options:
15 _terms:
16 description: command(s) to run.
17 required: True
18 notes:
19 - The given command is passed to a shell for execution, therefore all variables that are part of the command and
20 come from a remote/untrusted source MUST be sanitized using the P(ansible.builtin.quote#filter) filter to avoid
21 shell injection vulnerabilities. See the example section.
22 - Like all lookups this runs on the Ansible controller and is unaffected by other keywords, such as become,
23 so if you need to different permissions you must change the command or run Ansible as another user.
24 - Alternatively you can use a shell/command task that runs against localhost and registers the result.
25 - The directory of the play is used as the current working directory.
26 """
27
28 EXAMPLES = r"""
29 - name: raw result of running date command
30 ansible.builtin.debug:
31 msg: "{{ lookup('ansible.builtin.pipe', 'date') }}"
32
33 - name: Always use quote filter to make sure your variables are safe to use with shell
34 ansible.builtin.debug:
35 msg: "{{ lookup('ansible.builtin.pipe', 'getent passwd ' + myuser | quote ) }}"
36 """
37
38 RETURN = r"""
39 _string:
40 description:
41 - stdout from command
42 type: list
43 elements: str
44 """
45
46 import subprocess
47
48 from ansible.errors import AnsibleError
49 from ansible.plugins.lookup import LookupBase
50
51
52 class LookupModule(LookupBase):
53
54 def run(self, terms, variables=None, **kwargs):
55
56 ret = []
57 for term in terms:
58 # https://docs.python.org/3/library/subprocess.html#popen-constructor
59 #
60 # The shell argument (which defaults to False) specifies whether to use the
61 # shell as the program to execute. If shell is True, it is recommended to pass
62 # args as a string rather than as a sequence
63 #
64 # https://github.com/ansible/ansible/issues/6550
65 term = str(term)
66
67 p = subprocess.Popen(term, cwd=self._templar.basedir, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
68 (stdout, stderr) = p.communicate()
69 if p.returncode == 0:
70 ret.append(stdout.decode("utf-8").rstrip())
71 else:
72 raise AnsibleError("lookup_plugin.pipe(%s) returned %d" % (term, p.returncode))
73 return ret