Debian Codegraph @

lib/ansible/_internal/_ssh/_agent_launch.py

raw
1 from __future__ import annotations
2
3 import atexit
4 import os
5 import subprocess
6
7 from ansible import constants as C
8 from ansible._internal._errors import _alarm_timeout
9 from ansible._internal._ssh._ssh_agent import SshAgentClient
10 from ansible.cli import display
11 from ansible.errors import AnsibleError
12 from ansible.module_utils.common.process import get_bin_path
13
14 _SSH_AGENT_STDOUT_READ_TIMEOUT = 5 # seconds
15
16
17 def launch_ssh_agent() -> None:
18 """If configured via `SSH_AGENT`, launch an ssh-agent for Ansible's use and/or verify access to an existing one."""
19 try:
20 _launch_ssh_agent()
21 except Exception as ex:
22 raise AnsibleError("Failed to launch ssh agent.") from ex
23
24
25 def _launch_ssh_agent() -> None:
26 ssh_agent_cfg = C.config.get_config_value('SSH_AGENT')
27
28 match ssh_agent_cfg:
29 case 'none':
30 display.debug('SSH_AGENT set to none')
31 return
32 case 'auto':
33 try:
34 ssh_agent_bin = get_bin_path(C.config.get_config_value('SSH_AGENT_EXECUTABLE'))
35 except ValueError as e:
36 raise AnsibleError('SSH_AGENT set to auto, but cannot find ssh-agent binary.') from e
37
38 ssh_agent_dir = os.path.join(C.DEFAULT_LOCAL_TMP, 'ssh_agent')
39 os.mkdir(ssh_agent_dir, 0o700)
40 sock = os.path.join(ssh_agent_dir, 'agent.sock')
41 display.vvv('SSH_AGENT: starting...')
42
43 try:
44 p = subprocess.Popen(
45 [ssh_agent_bin, '-D', '-s', '-a', sock],
46 stdin=subprocess.PIPE,
47 stdout=subprocess.PIPE,
48 stderr=subprocess.PIPE,
49 text=True,
50 )
51 except OSError as e:
52 raise AnsibleError('Could not start ssh-agent.') from e
53
54 atexit.register(p.terminate)
55
56 help_text = f'The ssh-agent {ssh_agent_bin!r} might be an incompatible agent.'
57 expected_stdout = 'SSH_AUTH_SOCK'
58
59 try:
60 with _alarm_timeout.AnsibleTimeoutError.alarm_timeout(_SSH_AGENT_STDOUT_READ_TIMEOUT):
61 stdout = p.stdout.read(len(expected_stdout))
62 except _alarm_timeout.AnsibleTimeoutError as e:
63 display.error_as_warning(
64 msg=f'Timed out waiting for expected stdout {expected_stdout!r} from ssh-agent.',
65 exception=e,
66 help_text=help_text,
67 )
68 else:
69 if stdout != expected_stdout:
70 display.warning(
71 msg=f'The ssh-agent output {stdout!r} did not match expected {expected_stdout!r}.',
72 help_text=help_text,
73 )
74
75 if p.poll() is not None:
76 raise AnsibleError(
77 message='The ssh-agent terminated prematurely.',
78 help_text=f'{help_text}\n\nReturn Code: {p.returncode}\nStandard Error:\n{p.stderr.read()}',
79 )
80
81 display.vvv(f'SSH_AGENT: ssh-agent[{p.pid}] started and bound to {sock}')
82 case _:
83 sock = ssh_agent_cfg
84
85 try:
86 with SshAgentClient(sock) as client:
87 client.list()
88 except Exception as e:
89 raise AnsibleError(f'Could not communicate with ssh-agent using auth sock {sock!r}.') from e
90
91 os.environ['SSH_AUTH_SOCK'] = os.environ['ANSIBLE_SSH_AGENT'] = sock