Debian Codegraph @

ansible_collections/community/general/plugins/connection/saltstack.py

raw
1 # Based on local.py (c) 2012, Michael DeHaan <[email protected]>
2 # Based on chroot.py (c) 2013, Maykel Moya <[email protected]>
3 # Based on func.py
4 # Copyright (c) 2014, Michael Scherer <[email protected]>
5 # Copyright (c) 2017 Ansible Project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 author: Michael Scherer (@mscherer) <[email protected]>
13 name: saltstack
14 short_description: Allow ansible to piggyback on salt minions
15 description:
16 - Run commands or put/fetch files to Salt minions by using the local Salt master as transport.
17 - Ansible must run directly on the Salt master; this plugin uses C(salt.client.LocalClient)
18 and does not support connecting to a remote Salt master.
19 requirements:
20 - the C(salt) Python package must be installed on the Salt master (the Ansible controller)
21 options:
22 remote_addr:
23 description:
24 - The Salt minion ID to target.
25 type: string
26 default: inventory_hostname
27 vars:
28 - name: inventory_hostname
29 - name: ansible_host
30 notes:
31 - Ansible must be run from the Salt master host; the plugin cannot reach a remote Salt master.
32 - The inventory hostname (or O(remote_addr)) is treated as the Salt minion ID, not as a DNS
33 name or IP address.
34 - The Salt master and its minion keys must already be configured and accepted before using
35 this connection plugin.
36 - File transfer via P(community.general.saltstack#connection) uses C(hashutil.base64_decodefile)
37 (put) and C(cp.get_file_str) (fetch); these Salt execution modules must be available on
38 the targeted minions.
39 """
40
41 import base64
42 import os
43
44 from ansible import errors
45 from ansible.plugins.connection import ConnectionBase
46
47 HAVE_SALTSTACK = False
48 try:
49 import salt.client as sc
50
51 HAVE_SALTSTACK = True
52 except ImportError:
53 pass
54
55
56 class Connection(ConnectionBase):
57 """Salt-based connections"""
58
59 has_pipelining = False
60 # while the name of the product is salt, naming that module salt cause
61 # trouble with module import
62 transport = "community.general.saltstack"
63
64 def __init__(self, play_context, new_stdin, *args, **kwargs):
65 super().__init__(play_context, new_stdin, *args, **kwargs)
66 self.host = self._play_context.remote_addr
67
68 def _connect(self):
69 if not HAVE_SALTSTACK:
70 raise errors.AnsibleError("saltstack is not installed")
71
72 self.client = sc.LocalClient()
73 self._connected = True
74 return self
75
76 def exec_command(self, cmd, in_data=None, sudoable=False):
77 """run a command on the remote minion"""
78 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
79
80 if in_data:
81 raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
82
83 self._display.vvv(f"EXEC {cmd}", host=self.host)
84 # need to add 'true;' to work around https://github.com/saltstack/salt/issues/28077
85 res = self.client.cmd(self.host, "cmd.exec_code_all", ["bash", f"true;{cmd}"])
86 if self.host not in res:
87 raise errors.AnsibleError(
88 f"Minion {self.host} didn't answer, check if salt-minion is running and the name is correct"
89 )
90
91 p = res[self.host]
92 return p["retcode"], p["stdout"], p["stderr"]
93
94 @staticmethod
95 def _normalize_path(path, prefix):
96 if not path.startswith(os.path.sep):
97 path = os.path.join(os.path.sep, path)
98 normpath = os.path.normpath(path)
99 return os.path.join(prefix, normpath[1:])
100
101 def put_file(self, in_path, out_path):
102 """transfer a file from local to remote"""
103
104 super().put_file(in_path, out_path)
105
106 out_path = self._normalize_path(out_path, "/")
107 self._display.vvv(f"PUT {in_path} TO {out_path}", host=self.host)
108 with open(in_path, "rb") as in_fh:
109 content = in_fh.read()
110 self.client.cmd(self.host, "hashutil.base64_decodefile", [base64.b64encode(content), out_path])
111
112 # TODO test it
113 def fetch_file(self, in_path, out_path):
114 """fetch a file from remote to local"""
115
116 super().fetch_file(in_path, out_path)
117
118 in_path = self._normalize_path(in_path, "/")
119 self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self.host)
120 content = self.client.cmd(self.host, "cp.get_file_str", [in_path])[self.host]
121 open(out_path, "wb").write(content)
122
123 def close(self):
124 """terminate the connection; nothing to do here"""
125 pass