summaryrefslogtreecommitdiffstats
path: root/test/lib/ansible_test/_internal/bootstrap.py
blob: a9dd6370ee33d2a3e07b86eb34a795364b28f763 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""Bootstrapping for test hosts."""
from __future__ import annotations

import dataclasses
import os
import typing as t

from .io import (
    read_text_file,
)

from .util import (
    ANSIBLE_TEST_TARGET_ROOT,
)

from .util_common import (
    ShellScriptTemplate,
    set_shebang,
)

from .core_ci import (
    SshKey,
)


@dataclasses.dataclass
class Bootstrap:
    """Base class for bootstrapping systems."""

    controller: bool
    python_interpreters: dict[str, str]
    ssh_key: SshKey

    @property
    def bootstrap_type(self) -> str:
        """The bootstrap type to pass to the bootstrapping script."""
        return self.__class__.__name__.replace('Bootstrap', '').lower()

    def get_variables(self) -> dict[str, t.Union[str, list[str]]]:
        """The variables to template in the bootstrapping script."""
        return dict(
            bootstrap_type=self.bootstrap_type,
            controller='yes' if self.controller else '',
            python_interpreters=[f'{key}:{value}' for key, value in self.python_interpreters.items()],
            ssh_key_type=self.ssh_key.KEY_TYPE,
            ssh_private_key=self.ssh_key.key_contents,
            ssh_public_key=self.ssh_key.pub_contents,
        )

    def get_script(self) -> str:
        """Return a shell script to bootstrap the specified host."""
        path = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'bootstrap.sh')

        content = read_text_file(path)
        content = set_shebang(content, '/bin/sh')

        template = ShellScriptTemplate(content)

        variables = self.get_variables()

        script = template.substitute(**variables)

        return script


@dataclasses.dataclass
class BootstrapDocker(Bootstrap):
    """Bootstrap docker instances."""

    def get_variables(self) -> dict[str, t.Union[str, list[str]]]:
        """The variables to template in the bootstrapping script."""
        variables = super().get_variables()

        variables.update(
            platform='',
            platform_version='',
        )

        return variables


@dataclasses.dataclass
class BootstrapRemote(Bootstrap):
    """Bootstrap remote instances."""

    platform: str
    platform_version: str

    def get_variables(self) -> dict[str, t.Union[str, list[str]]]:
        """The variables to template in the bootstrapping script."""
        variables = super().get_variables()

        variables.update(
            platform=self.platform,
            platform_version=self.platform_version,
        )

        return variables