Debian Codegraph @

test/lib/ansible_test/_internal/bootstrap.py

raw
1 """Bootstrapping for test hosts."""
2
3 from __future__ import annotations
4
5 import dataclasses
6 import os
7 import typing as t
8
9 from .io import (
10 read_text_file,
11 )
12
13 from .util import (
14 ANSIBLE_TEST_TARGET_ROOT,
15 )
16
17 from .util_common import (
18 ShellScriptTemplate,
19 set_shebang,
20 )
21
22 from .core_ci import (
23 SshKey,
24 )
25
26
27 @dataclasses.dataclass(kw_only=True)
28 class Bootstrap:
29 """Base class for bootstrapping systems."""
30
31 controller: bool
32 python_interpreters: dict[str, str]
33 ssh_key: SshKey
34 powershell_versions: list[str]
35
36 @property
37 def bootstrap_type(self) -> str:
38 """The bootstrap type to pass to the bootstrapping script."""
39 return self.__class__.__name__.replace('Bootstrap', '').lower()
40
41 def get_variables(self) -> dict[str, t.Union[str, list[str]]]:
42 """The variables to template in the bootstrapping script."""
43 return dict(
44 bootstrap_type=self.bootstrap_type,
45 controller='yes' if self.controller else '',
46 python_interpreters=[f'{key}:{value}' for key, value in self.python_interpreters.items()],
47 ssh_key_type=self.ssh_key.KEY_TYPE,
48 ssh_private_key=self.ssh_key.key_contents,
49 ssh_public_key=self.ssh_key.pub_contents,
50 powershell_versions=self.powershell_versions,
51 )
52
53 def get_script(self) -> str:
54 """Return a shell script to bootstrap the specified host."""
55 path = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'bootstrap.sh')
56
57 content = read_text_file(path)
58 content = set_shebang(content, '/bin/sh')
59
60 template = ShellScriptTemplate(content)
61
62 variables = self.get_variables()
63
64 script = template.substitute(**variables)
65
66 return script
67
68
69 @dataclasses.dataclass(kw_only=True)
70 class BootstrapDocker(Bootstrap):
71 """Bootstrap docker instances."""
72
73 def get_variables(self) -> dict[str, t.Union[str, list[str]]]:
74 """The variables to template in the bootstrapping script."""
75 variables = super().get_variables()
76
77 variables.update(
78 platform='',
79 platform_version='',
80 )
81
82 return variables
83
84
85 @dataclasses.dataclass(kw_only=True)
86 class BootstrapRemote(Bootstrap):
87 """Bootstrap remote instances."""
88
89 platform: str
90 platform_version: str
91
92 def get_variables(self) -> dict[str, t.Union[str, list[str]]]:
93 """The variables to template in the bootstrapping script."""
94 variables = super().get_variables()
95
96 variables.update(
97 platform=self.platform,
98 platform_version=self.platform_version,
99 )
100
101 return variables