Debian Codegraph @

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

raw
1 # Copyright (c) 2016 Matt Clay <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 author: Matt Clay (@mattclay) <[email protected]>
10 name: lxd
11 short_description: Run tasks in LXD instances using C(lxc) CLI
12 description:
13 - Run commands or put/fetch files to an existing instance using C(lxc) CLI.
14 options:
15 remote_addr:
16 description:
17 - Instance (container/VM) identifier.
18 - Since community.general 8.0.0, a FQDN can be provided; in that case, the first component (the part before C(.)) is
19 used as the instance identifier.
20 type: string
21 default: inventory_hostname
22 vars:
23 - name: inventory_hostname
24 - name: ansible_host
25 - name: ansible_lxd_host
26 executable:
27 description:
28 - Shell to use for execution inside instance.
29 type: string
30 default: /bin/sh
31 vars:
32 - name: ansible_executable
33 - name: ansible_lxd_executable
34 lxd_become_method:
35 description:
36 - Become command used to switch to a non-root user.
37 - Is only used when O(remote_user) is not V(root).
38 type: str
39 default: /bin/su
40 vars:
41 - name: lxd_become_method
42 version_added: 10.4.0
43 remote:
44 description:
45 - Name of the LXD remote to use.
46 type: string
47 default: local
48 vars:
49 - name: ansible_lxd_remote
50 version_added: 2.0.0
51 remote_user:
52 description:
53 - User to login/authenticate as.
54 - Can be set from the CLI with the C(--user) or C(-u) options.
55 type: string
56 default: root
57 vars:
58 - name: ansible_user
59 env:
60 - name: ANSIBLE_REMOTE_USER
61 ini:
62 - section: defaults
63 key: remote_user
64 keyword:
65 - name: remote_user
66 version_added: 10.4.0
67 project:
68 description:
69 - Name of the LXD project to use.
70 type: string
71 vars:
72 - name: ansible_lxd_project
73 version_added: 2.0.0
74 """
75
76 import os
77 from subprocess import PIPE, Popen
78
79 from ansible.errors import AnsibleConnectionFailure, AnsibleError, AnsibleFileNotFound
80 from ansible.module_utils.common.process import get_bin_path
81 from ansible.module_utils.common.text.converters import to_bytes, to_text
82 from ansible.plugins.connection import ConnectionBase
83
84
85 class Connection(ConnectionBase):
86 """lxd based connections"""
87
88 transport = "community.general.lxd"
89 has_pipelining = True
90
91 def __init__(self, play_context, new_stdin, *args, **kwargs):
92 super().__init__(play_context, new_stdin, *args, **kwargs)
93
94 try:
95 self._lxc_cmd = get_bin_path("lxc")
96 except ValueError as e:
97 raise AnsibleError("lxc command not found in PATH") from e
98
99 def _host(self):
100 """translate remote_addr to lxd (short) hostname"""
101 return self.get_option("remote_addr").split(".", 1)[0]
102
103 def _connect(self):
104 """connect to lxd (nothing to do here)"""
105 super()._connect()
106
107 if not self._connected:
108 self._display.vvv(f"ESTABLISH LXD CONNECTION FOR USER: {self.get_option('remote_user')}", host=self._host())
109 self._connected = True
110
111 def _build_command(self, cmd) -> list[str]:
112 """build the command to execute on the lxd host"""
113
114 exec_cmd: list[str] = [self._lxc_cmd]
115
116 if self.get_option("project"):
117 exec_cmd.extend(["--project", self.get_option("project")])
118
119 exec_cmd.extend(["exec", f"{self.get_option('remote')}:{self._host()}", "--"])
120
121 if self.get_option("remote_user") != "root":
122 self._display.vvv(
123 f"INFO: Running as non-root user: {self.get_option('remote_user')}, \
124 trying to run 'lxc exec' with become method: {self.get_option('lxd_become_method')}",
125 host=self._host(),
126 )
127 exec_cmd.extend([self.get_option("lxd_become_method"), self.get_option("remote_user"), "-c"])
128
129 exec_cmd.extend([self.get_option("executable"), "-c", cmd])
130
131 return exec_cmd
132
133 def exec_command(self, cmd, in_data=None, sudoable=True):
134 """execute a command on the lxd host"""
135 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
136
137 self._display.vvv(f"EXEC {cmd}", host=self._host())
138
139 local_cmd = self._build_command(cmd)
140 self._display.vvvvv(f"EXEC {local_cmd}", host=self._host())
141
142 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
143 in_data = to_bytes(in_data, errors="surrogate_or_strict", nonstring="passthru")
144
145 process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
146 stdout, stderr = process.communicate(in_data)
147
148 stdout = to_text(stdout)
149 stderr = to_text(stderr)
150
151 self._display.vvvvv(f"EXEC lxc output: {stdout} {stderr}", host=self._host())
152
153 if "is not running" in stderr:
154 raise AnsibleConnectionFailure(f"instance not running: {self._host()}")
155
156 if stderr.strip() == "Error: Instance not found" or stderr.strip() == "error: not found":
157 raise AnsibleConnectionFailure(f"instance not found: {self._host()}")
158
159 return process.returncode, stdout, stderr
160
161 def _get_remote_uid_gid(self) -> tuple[int, int]:
162 """Get the user and group ID of 'remote_user' from the instance."""
163
164 rc, uid_out, err = self.exec_command("/bin/id -u")
165 if rc != 0:
166 raise AnsibleError(f"Failed to get remote uid for user {self.get_option('remote_user')}: {err}")
167 uid = uid_out.strip()
168
169 rc, gid_out, err = self.exec_command("/bin/id -g")
170 if rc != 0:
171 raise AnsibleError(f"Failed to get remote gid for user {self.get_option('remote_user')}: {err}")
172 gid = gid_out.strip()
173
174 return int(uid), int(gid)
175
176 def put_file(self, in_path, out_path):
177 """put a file from local to lxd"""
178 super().put_file(in_path, out_path)
179
180 self._display.vvv(f"PUT {in_path} TO {out_path}", host=self._host())
181
182 if not os.path.isfile(to_bytes(in_path, errors="surrogate_or_strict")):
183 raise AnsibleFileNotFound(f"input path is not a file: {in_path}")
184
185 local_cmd = [self._lxc_cmd]
186 if self.get_option("project"):
187 local_cmd.extend(["--project", self.get_option("project")])
188
189 if self.get_option("remote_user") != "root":
190 uid, gid = self._get_remote_uid_gid()
191 local_cmd.extend(
192 [
193 "file",
194 "push",
195 "--uid",
196 str(uid),
197 "--gid",
198 str(gid),
199 in_path,
200 f"{self.get_option('remote')}:{self._host()}/{out_path}",
201 ]
202 )
203 else:
204 local_cmd.extend(
205 [
206 "file",
207 "push",
208 in_path,
209 f"{self.get_option('remote')}:{self._host()}/{out_path}",
210 ]
211 )
212
213 self._display.vvvvv(f"PUT {local_cmd}", host=self._host())
214
215 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
216
217 process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
218 process.communicate()
219
220 def fetch_file(self, in_path, out_path):
221 """fetch a file from lxd to local"""
222 super().fetch_file(in_path, out_path)
223
224 self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self._host())
225
226 local_cmd = [self._lxc_cmd]
227 if self.get_option("project"):
228 local_cmd.extend(["--project", self.get_option("project")])
229 local_cmd.extend(["file", "pull", f"{self.get_option('remote')}:{self._host()}/{in_path}", out_path])
230
231 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
232
233 process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
234 process.communicate()
235
236 def close(self):
237 """close the connection (nothing to do here)"""
238 super().close()
239
240 self._connected = False