| 1 |
# Copyright (c) 2019, Ximon Eighteen <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
name: docker_machine |
| 9 |
author: Ximon Eighteen (@ximon18) |
| 10 |
short_description: Docker Machine inventory source |
| 11 |
requirements: |
| 12 |
- L(Docker Machine,https://docs.docker.com/machine/) |
| 13 |
extends_documentation_fragment: |
| 14 |
- ansible.builtin.constructed |
| 15 |
- community.library_inventory_filtering_v1.inventory_filter |
| 16 |
description: |
| 17 |
- Get inventory hosts from Docker Machine. |
| 18 |
- Uses a YAML configuration file that ends with V(docker_machine.(yml|yaml\)). |
| 19 |
- The plugin sets standard host variables C(ansible_host), C(ansible_port), C(ansible_user) and C(ansible_ssh_private_key). |
| 20 |
- The plugin stores the Docker Machine 'env' output variables in C(dm_) prefixed host variables. |
| 21 |
notes: |
| 22 |
- The configuration file must be a YAML file whose filename ends with V(docker_machine.yml) or V(docker_machine.yaml). Other |
| 23 |
filenames will not be accepted. |
| 24 |
options: |
| 25 |
plugin: |
| 26 |
description: Token that ensures this is a source file for the C(docker_machine) plugin. |
| 27 |
required: true |
| 28 |
choices: ['docker_machine', 'community.docker.docker_machine'] |
| 29 |
daemon_env: |
| 30 |
description: |
| 31 |
- Whether docker daemon connection environment variables should be fetched, and how to behave if they cannot be fetched. |
| 32 |
- With V(require) and V(require-silently), fetch them and skip any host for which they cannot be fetched. A warning |
| 33 |
will be issued for any skipped host if the choice is V(require). |
| 34 |
- With V(optional) and V(optional-silently), fetch them and not skip hosts for which they cannot be fetched. A warning |
| 35 |
will be issued for hosts where they cannot be fetched if the choice is V(optional). |
| 36 |
- With V(skip), do not attempt to fetch the docker daemon connection environment variables. |
| 37 |
- If fetched successfully, the variables will be prefixed with C(dm_) and stored as host variables. |
| 38 |
type: str |
| 39 |
choices: |
| 40 |
- require |
| 41 |
- require-silently |
| 42 |
- optional |
| 43 |
- optional-silently |
| 44 |
- skip |
| 45 |
default: require |
| 46 |
running_required: |
| 47 |
description: |
| 48 |
- When V(true), hosts which Docker Machine indicates are in a state other than C(running) will be skipped. |
| 49 |
type: bool |
| 50 |
default: true |
| 51 |
verbose_output: |
| 52 |
description: |
| 53 |
- When V(true), include all available nodes metadata (for example C(Image), C(Region), C(Size)) as a JSON object named |
| 54 |
C(docker_machine_node_attributes). |
| 55 |
type: bool |
| 56 |
default: true |
| 57 |
filters: |
| 58 |
version_added: 3.5.0 |
| 59 |
""" |
| 60 |
|
| 61 |
EXAMPLES = """ |
| 62 |
--- |
| 63 |
# Minimal example |
| 64 |
plugin: community.docker.docker_machine |
| 65 |
|
| 66 |
--- |
| 67 |
# Example using constructed features to create a group per Docker Machine driver |
| 68 |
# (https://docs.docker.com/machine/drivers/), for example: |
| 69 |
# $ docker-machine create --driver digitalocean ... mymachine |
| 70 |
# $ ansible-inventory -i ./path/to/docker-machine.yml --host=mymachine |
| 71 |
# { |
| 72 |
# ... |
| 73 |
# "digitalocean": { |
| 74 |
# "hosts": [ |
| 75 |
# "mymachine" |
| 76 |
# ] |
| 77 |
# ... |
| 78 |
# } |
| 79 |
plugin: community.docker.docker_machine |
| 80 |
strict: false |
| 81 |
keyed_groups: |
| 82 |
- separator: '' |
| 83 |
key: docker_machine_node_attributes.DriverName |
| 84 |
|
| 85 |
--- |
| 86 |
# Example grouping hosts by Digital Machine tag |
| 87 |
plugin: community.docker.docker_machine |
| 88 |
strict: false |
| 89 |
keyed_groups: |
| 90 |
- prefix: tag |
| 91 |
key: 'dm_tags' |
| 92 |
|
| 93 |
--- |
| 94 |
# Example using compose to override the default SSH behaviour of asking the user to accept the remote host key |
| 95 |
plugin: community.docker.docker_machine |
| 96 |
compose: |
| 97 |
ansible_ssh_common_args: '"-o StrictHostKeyChecking=accept-new"' |
| 98 |
""" |
| 99 |
|
| 100 |
import json |
| 101 |
import re |
| 102 |
import subprocess |
| 103 |
import typing as t |
| 104 |
|
| 105 |
from ansible.errors import AnsibleError |
| 106 |
from ansible.module_utils.common.process import get_bin_path |
| 107 |
from ansible.module_utils.common.text.converters import to_text |
| 108 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 109 |
from ansible.utils.display import Display |
| 110 |
from ansible_collections.community.library_inventory_filtering_v1.plugins.plugin_utils.inventory_filter import ( |
| 111 |
filter_host, |
| 112 |
parse_filters, |
| 113 |
) |
| 114 |
|
| 115 |
from ansible_collections.community.docker.plugins.plugin_utils._unsafe import ( |
| 116 |
make_unsafe, |
| 117 |
) |
| 118 |
|
| 119 |
if t.TYPE_CHECKING: |
| 120 |
from ansible.inventory.data import InventoryData |
| 121 |
from ansible.parsing.dataloader import DataLoader |
| 122 |
|
| 123 |
DaemonEnv = t.Literal[ |
| 124 |
"require", "require-silently", "optional", "optional-silently", "skip" |
| 125 |
] |
| 126 |
|
| 127 |
|
| 128 |
display = Display() |
| 129 |
|
| 130 |
|
| 131 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 132 |
"""Host inventory parser for ansible using Docker machine as source.""" |
| 133 |
|
| 134 |
NAME = "community.docker.docker_machine" |
| 135 |
|
| 136 |
docker_machine_path: str | None = None |
| 137 |
|
| 138 |
def _run_command(self, args: list[str]) -> str: |
| 139 |
if not self.docker_machine_path: |
| 140 |
try: |
| 141 |
self.docker_machine_path = get_bin_path("docker-machine") |
| 142 |
except ValueError as e: |
| 143 |
raise AnsibleError(to_text(e)) from e |
| 144 |
|
| 145 |
command = [self.docker_machine_path] |
| 146 |
command.extend(args) |
| 147 |
display.debug(f"Executing command {command}") |
| 148 |
try: |
| 149 |
result = subprocess.check_output(command) |
| 150 |
except subprocess.CalledProcessError as e: |
| 151 |
display.warning( |
| 152 |
f"Exception {type(e).__name__} caught while executing command {command}, this was the original exception: {e}" |
| 153 |
) |
| 154 |
raise e |
| 155 |
|
| 156 |
return to_text(result).strip() |
| 157 |
|
| 158 |
def _get_docker_daemon_variables(self, machine_name: str) -> list[tuple[str, str]]: |
| 159 |
""" |
| 160 |
Capture settings from Docker Machine that would be needed to connect to the remote Docker daemon installed on |
| 161 |
the Docker Machine remote host. Note: passing '--shell=sh' is a workaround for 'Error: Unknown shell'. |
| 162 |
""" |
| 163 |
try: |
| 164 |
env_lines = self._run_command( |
| 165 |
["env", "--shell=sh", machine_name] |
| 166 |
).splitlines() |
| 167 |
except subprocess.CalledProcessError: |
| 168 |
# This can happen when the machine is created but provisioning is incomplete |
| 169 |
return [] |
| 170 |
|
| 171 |
# example output of docker-machine env --shell=sh: |
| 172 |
# export DOCKER_TLS_VERIFY="1" |
| 173 |
# export DOCKER_HOST="tcp://134.209.204.160:2376" |
| 174 |
# export DOCKER_CERT_PATH="/root/.docker/machine/machines/routinator" |
| 175 |
# export DOCKER_MACHINE_NAME="routinator" |
| 176 |
# # Run this command to configure your shell: |
| 177 |
# # eval $(docker-machine env --shell=bash routinator) |
| 178 |
|
| 179 |
# capture any of the DOCKER_xxx variables that were output and create Ansible host vars |
| 180 |
# with the same name and value but with a dm_ name prefix. |
| 181 |
env_vars = [] |
| 182 |
for line in env_lines: |
| 183 |
match = re.search('(DOCKER_[^=]+)="([^"]+)"', line) |
| 184 |
if match: |
| 185 |
env_var_name = match.group(1) |
| 186 |
env_var_value = match.group(2) |
| 187 |
env_vars.append((env_var_name, env_var_value)) |
| 188 |
|
| 189 |
return env_vars |
| 190 |
|
| 191 |
def _get_machine_names(self) -> list[str]: |
| 192 |
# Filter out machines that are not in the Running state as we probably cannot do anything useful actions |
| 193 |
# with them. |
| 194 |
ls_command = ["ls", "-q"] |
| 195 |
if self.get_option("running_required"): |
| 196 |
ls_command.extend(["--filter", "state=Running"]) |
| 197 |
|
| 198 |
try: |
| 199 |
ls_lines = self._run_command(ls_command) |
| 200 |
except subprocess.CalledProcessError: |
| 201 |
return [] |
| 202 |
|
| 203 |
return ls_lines.splitlines() |
| 204 |
|
| 205 |
def _inspect_docker_machine_host(self, node: str) -> t.Any | None: |
| 206 |
try: |
| 207 |
inspect_lines = self._run_command(["inspect", node]) |
| 208 |
except subprocess.CalledProcessError: |
| 209 |
return None |
| 210 |
|
| 211 |
return json.loads(inspect_lines) |
| 212 |
|
| 213 |
def _ip_addr_docker_machine_host(self, node: str) -> t.Any | None: |
| 214 |
try: |
| 215 |
ip_addr = self._run_command(["ip", node]) |
| 216 |
except subprocess.CalledProcessError: |
| 217 |
return None |
| 218 |
|
| 219 |
return ip_addr |
| 220 |
|
| 221 |
def _should_skip_host( |
| 222 |
self, |
| 223 |
machine_name: str, |
| 224 |
env_var_tuples: list[tuple[str, str]], |
| 225 |
daemon_env: DaemonEnv, |
| 226 |
) -> bool: |
| 227 |
if not env_var_tuples: |
| 228 |
warning_prefix = f"Unable to fetch Docker daemon env vars from Docker Machine for host {machine_name}" |
| 229 |
if daemon_env in ("require", "require-silently"): |
| 230 |
if daemon_env == "require": |
| 231 |
display.warning(f"{warning_prefix}: host will be skipped") |
| 232 |
return True |
| 233 |
if daemon_env == "optional": |
| 234 |
display.warning( |
| 235 |
f"{warning_prefix}: host will lack dm_DOCKER_xxx variables" |
| 236 |
) |
| 237 |
# daemon_env is 'optional-silently' |
| 238 |
return False |
| 239 |
|
| 240 |
def _populate(self) -> None: |
| 241 |
if self.inventory is None: |
| 242 |
raise AssertionError("Inventory must be there") |
| 243 |
|
| 244 |
daemon_env: DaemonEnv = self.get_option("daemon_env") |
| 245 |
filters = parse_filters(self.get_option("filters")) |
| 246 |
try: |
| 247 |
for node in self._get_machine_names(): |
| 248 |
node_attrs = self._inspect_docker_machine_host(node) |
| 249 |
if not node_attrs: |
| 250 |
continue |
| 251 |
|
| 252 |
unsafe_node_attrs = make_unsafe(node_attrs) |
| 253 |
|
| 254 |
machine_name = unsafe_node_attrs["Driver"]["MachineName"] |
| 255 |
if not filter_host(self, machine_name, unsafe_node_attrs, filters): |
| 256 |
continue |
| 257 |
|
| 258 |
# query `docker-machine env` to obtain remote Docker daemon connection settings in the form of commands |
| 259 |
# that could be used to set environment variables to influence a local Docker client: |
| 260 |
if daemon_env == "skip": |
| 261 |
env_var_tuples = [] |
| 262 |
else: |
| 263 |
env_var_tuples = self._get_docker_daemon_variables(machine_name) |
| 264 |
if self._should_skip_host(machine_name, env_var_tuples, daemon_env): |
| 265 |
continue |
| 266 |
|
| 267 |
# add an entry in the inventory for this host |
| 268 |
self.inventory.add_host(machine_name) |
| 269 |
|
| 270 |
# check for valid ip address from inspect output, else explicitly use ip command to find host ip address |
| 271 |
# this works around an issue seen with Google Compute Platform where the IP address was not available |
| 272 |
# via the 'inspect' subcommand but was via the 'ip' subcomannd. |
| 273 |
if unsafe_node_attrs["Driver"]["IPAddress"]: |
| 274 |
ip_addr = unsafe_node_attrs["Driver"]["IPAddress"] |
| 275 |
else: |
| 276 |
ip_addr = self._ip_addr_docker_machine_host(node) |
| 277 |
|
| 278 |
# set standard Ansible remote host connection settings to details captured from `docker-machine` |
| 279 |
# see: https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html |
| 280 |
self.inventory.set_variable( |
| 281 |
machine_name, "ansible_host", make_unsafe(ip_addr) |
| 282 |
) |
| 283 |
self.inventory.set_variable( |
| 284 |
machine_name, "ansible_port", unsafe_node_attrs["Driver"]["SSHPort"] |
| 285 |
) |
| 286 |
self.inventory.set_variable( |
| 287 |
machine_name, "ansible_user", unsafe_node_attrs["Driver"]["SSHUser"] |
| 288 |
) |
| 289 |
self.inventory.set_variable( |
| 290 |
machine_name, |
| 291 |
"ansible_ssh_private_key_file", |
| 292 |
unsafe_node_attrs["Driver"]["SSHKeyPath"], |
| 293 |
) |
| 294 |
|
| 295 |
# set variables based on Docker Machine tags |
| 296 |
tags = unsafe_node_attrs["Driver"].get("Tags") or "" |
| 297 |
self.inventory.set_variable(machine_name, "dm_tags", make_unsafe(tags)) |
| 298 |
|
| 299 |
# set variables based on Docker Machine env variables |
| 300 |
for kv in env_var_tuples: |
| 301 |
self.inventory.set_variable( |
| 302 |
machine_name, f"dm_{kv[0]}", make_unsafe(kv[1]) |
| 303 |
) |
| 304 |
|
| 305 |
if self.get_option("verbose_output"): |
| 306 |
self.inventory.set_variable( |
| 307 |
machine_name, |
| 308 |
"docker_machine_node_attributes", |
| 309 |
unsafe_node_attrs, |
| 310 |
) |
| 311 |
|
| 312 |
# Use constructed if applicable |
| 313 |
strict = self.get_option("strict") |
| 314 |
|
| 315 |
# Composed variables |
| 316 |
self._set_composite_vars( |
| 317 |
self.get_option("compose"), |
| 318 |
unsafe_node_attrs, |
| 319 |
machine_name, |
| 320 |
strict=strict, |
| 321 |
) |
| 322 |
|
| 323 |
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group |
| 324 |
self._add_host_to_composed_groups( |
| 325 |
self.get_option("groups"), |
| 326 |
unsafe_node_attrs, |
| 327 |
machine_name, |
| 328 |
strict=strict, |
| 329 |
) |
| 330 |
|
| 331 |
# Create groups based on variable values and add the corresponding hosts to it |
| 332 |
self._add_host_to_keyed_groups( |
| 333 |
self.get_option("keyed_groups"), |
| 334 |
unsafe_node_attrs, |
| 335 |
machine_name, |
| 336 |
strict=strict, |
| 337 |
) |
| 338 |
|
| 339 |
except Exception as e: |
| 340 |
raise AnsibleError( |
| 341 |
f"Unable to fetch hosts from Docker Machine, this was the original exception: {e}" |
| 342 |
) from e |
| 343 |
|
| 344 |
def verify_file(self, path: str) -> bool: |
| 345 |
"""Return the possibility of a file being consumable by this plugin.""" |
| 346 |
return super().verify_file(path) and path.endswith( |
| 347 |
("docker_machine.yaml", "docker_machine.yml") |
| 348 |
) |
| 349 |
|
| 350 |
def parse( |
| 351 |
self, |
| 352 |
inventory: InventoryData, |
| 353 |
loader: DataLoader, |
| 354 |
path: str, |
| 355 |
cache: bool = True, |
| 356 |
) -> None: |
| 357 |
super().parse(inventory, loader, path, cache) |
| 358 |
self._read_config_data(path) |
| 359 |
self._populate() |