| 1 |
# Copyright (c) 2020, Felix Fontein <[email protected]> |
| 2 |
# For the parts taken from the docker inventory script: |
| 3 |
# Copyright (c) 2016, Paul Durivage <[email protected]> |
| 4 |
# Copyright (c) 2016, Chris Houseknecht <[email protected]> |
| 5 |
# Copyright (c) 2016, James Tanner <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
name: docker_containers |
| 13 |
short_description: Ansible dynamic inventory plugin for Docker containers |
| 14 |
version_added: 1.1.0 |
| 15 |
author: |
| 16 |
- Felix Fontein (@felixfontein) |
| 17 |
extends_documentation_fragment: |
| 18 |
- ansible.builtin.constructed |
| 19 |
- community.docker._docker.api_documentation |
| 20 |
- community.library_inventory_filtering_v1.inventory_filter |
| 21 |
description: |
| 22 |
- Reads inventories from the Docker API. |
| 23 |
- Uses a YAML configuration file that ends with V(docker.(yml|yaml\)). |
| 24 |
notes: |
| 25 |
- The configuration file must be a YAML file whose filename ends with V(docker.yml) or V(docker.yaml). Other filenames will |
| 26 |
not be accepted. |
| 27 |
options: |
| 28 |
plugin: |
| 29 |
description: |
| 30 |
- The name of this plugin, it should always be set to V(community.docker.docker_containers) for this plugin to recognize |
| 31 |
it as its own. |
| 32 |
type: str |
| 33 |
required: true |
| 34 |
choices: [community.docker.docker_containers] |
| 35 |
|
| 36 |
connection_type: |
| 37 |
description: |
| 38 |
- Which connection type to use the containers. |
| 39 |
- One way to connect to containers is to use SSH (V(ssh)). For this, the options O(default_ip) and O(private_ssh_port) |
| 40 |
are used. This requires that a SSH daemon is running inside the containers. |
| 41 |
- Alternatively, V(docker-cli) selects the P(community.docker.docker#connection) connection plugin, and V(docker-api) |
| 42 |
(default) selects the P(community.docker.docker_api#connection) connection plugin. |
| 43 |
- When V(docker-api) is used, all Docker daemon configuration values are passed from the inventory plugin to the connection |
| 44 |
plugin. This can be controlled with O(configure_docker_daemon). |
| 45 |
- Note that the P(community.docker.docker_api#connection) does B(not work with TCP TLS sockets)! |
| 46 |
See U(https://github.com/ansible-collections/community.docker/issues/605) for more information. |
| 47 |
type: str |
| 48 |
default: docker-api |
| 49 |
choices: |
| 50 |
- ssh |
| 51 |
- docker-cli |
| 52 |
- docker-api |
| 53 |
|
| 54 |
configure_docker_daemon: |
| 55 |
description: |
| 56 |
- Whether to pass all Docker daemon configuration from the inventory plugin to the connection plugin. |
| 57 |
- Only used when O(connection_type=docker-api). |
| 58 |
type: bool |
| 59 |
default: true |
| 60 |
version_added: 1.8.0 |
| 61 |
|
| 62 |
verbose_output: |
| 63 |
description: |
| 64 |
- Toggle to (not) include all available inspection metadata. |
| 65 |
- Note that all top-level keys will be transformed to the format C(docker_xxx). For example, C(HostConfig) is converted |
| 66 |
to C(docker_hostconfig). |
| 67 |
- If this is V(false), these values can only be used during O(compose), O(groups), and O(keyed_groups). |
| 68 |
- The C(docker) inventory script always added these variables, so for compatibility set this to V(true). |
| 69 |
type: bool |
| 70 |
default: false |
| 71 |
|
| 72 |
default_ip: |
| 73 |
description: |
| 74 |
- The IP address to assign to ansible_host when the container's SSH port is mapped to interface '0.0.0.0'. |
| 75 |
- Only used if O(connection_type) is V(ssh). |
| 76 |
type: str |
| 77 |
default: 127.0.0.1 |
| 78 |
|
| 79 |
private_ssh_port: |
| 80 |
description: |
| 81 |
- The port containers use for SSH. |
| 82 |
- Only used if O(connection_type) is V(ssh). |
| 83 |
type: int |
| 84 |
default: 22 |
| 85 |
|
| 86 |
add_legacy_groups: |
| 87 |
description: |
| 88 |
- 'Add the same groups as the C(docker) inventory script does. These are the following:' |
| 89 |
- 'C(<container id>): contains the container of this ID.' |
| 90 |
- 'C(<container name>): contains the container that has this name.' |
| 91 |
- 'C(<container short id>): contains the containers that have this short ID (first 13 letters of ID).' |
| 92 |
- 'C(image_<image name>): contains the containers that have the image C(<image name>).' |
| 93 |
- 'C(stack_<stack name>): contains the containers that belong to the stack C(<stack name>).' |
| 94 |
- 'C(service_<service name>): contains the containers that belong to the service C(<service name>).' |
| 95 |
- 'C(<docker_host>): contains the containers which belong to the Docker daemon O(docker_host). Useful if you run this |
| 96 |
plugin against multiple Docker daemons.' |
| 97 |
- 'C(running): contains all containers that are running.' |
| 98 |
- 'C(stopped): contains all containers that are not running.' |
| 99 |
- If this is not set to V(true), you should use keyed groups to add the containers to groups. See the examples for how |
| 100 |
to do that. |
| 101 |
type: bool |
| 102 |
default: false |
| 103 |
|
| 104 |
filters: |
| 105 |
version_added: 3.5.0 |
| 106 |
""" |
| 107 |
|
| 108 |
EXAMPLES = """ |
| 109 |
--- |
| 110 |
# Minimal example using local Docker daemon |
| 111 |
plugin: community.docker.docker_containers |
| 112 |
docker_host: unix:///var/run/docker.sock |
| 113 |
|
| 114 |
--- |
| 115 |
# Minimal example using remote Docker daemon |
| 116 |
plugin: community.docker.docker_containers |
| 117 |
docker_host: tcp://my-docker-host:2375 |
| 118 |
|
| 119 |
--- |
| 120 |
# Example using remote Docker daemon with unverified TLS |
| 121 |
plugin: community.docker.docker_containers |
| 122 |
docker_host: tcp://my-docker-host:2376 |
| 123 |
tls: true |
| 124 |
|
| 125 |
--- |
| 126 |
# Example using remote Docker daemon with verified TLS and client certificate verification |
| 127 |
plugin: community.docker.docker_containers |
| 128 |
docker_host: tcp://my-docker-host:2376 |
| 129 |
validate_certs: true |
| 130 |
ca_path: /somewhere/ca.pem |
| 131 |
client_key: /somewhere/key.pem |
| 132 |
client_cert: /somewhere/cert.pem |
| 133 |
|
| 134 |
--- |
| 135 |
# Example using constructed features to create groups |
| 136 |
plugin: community.docker.docker_containers |
| 137 |
docker_host: tcp://my-docker-host:2375 |
| 138 |
strict: false |
| 139 |
keyed_groups: |
| 140 |
# Add containers with primary network foo to a network_foo group |
| 141 |
- prefix: network |
| 142 |
key: 'docker_hostconfig.NetworkMode' |
| 143 |
# Add Linux hosts to an os_linux group |
| 144 |
- prefix: os |
| 145 |
key: docker_platform |
| 146 |
|
| 147 |
--- |
| 148 |
# Example using SSH connection with an explicit fallback for when port 22 has not been |
| 149 |
# exported: use container name as ansible_ssh_host and 22 as ansible_ssh_port |
| 150 |
plugin: community.docker.docker_containers |
| 151 |
connection_type: ssh |
| 152 |
compose: |
| 153 |
ansible_ssh_host: ansible_ssh_host | default(docker_name[1:], true) |
| 154 |
ansible_ssh_port: ansible_ssh_port | default(22, true) |
| 155 |
|
| 156 |
--- |
| 157 |
# Only consider containers which have a label 'foo', or whose name starts with 'a' |
| 158 |
plugin: community.docker.docker_containers |
| 159 |
filters: |
| 160 |
# Accept all containers which have a label called 'foo' |
| 161 |
- include: >- |
| 162 |
"foo" in docker_config.Labels |
| 163 |
# Next accept all containers whose inventory_hostname starts with 'a' |
| 164 |
- include: >- |
| 165 |
inventory_hostname.startswith("a") |
| 166 |
# Exclude all containers that did not match any of the above filters |
| 167 |
- exclude: true |
| 168 |
""" |
| 169 |
|
| 170 |
import re |
| 171 |
import typing as t |
| 172 |
|
| 173 |
from ansible.errors import AnsibleError |
| 174 |
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable |
| 175 |
from ansible_collections.community.library_inventory_filtering_v1.plugins.plugin_utils.inventory_filter import ( |
| 176 |
filter_host, |
| 177 |
parse_filters, |
| 178 |
) |
| 179 |
|
| 180 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 181 |
APIError, |
| 182 |
DockerException, |
| 183 |
) |
| 184 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 185 |
RequestException, |
| 186 |
) |
| 187 |
from ansible_collections.community.docker.plugins.module_utils._util import ( |
| 188 |
DOCKER_COMMON_ARGS_VARS, |
| 189 |
) |
| 190 |
from ansible_collections.community.docker.plugins.plugin_utils._common_api import ( |
| 191 |
AnsibleDockerClient, |
| 192 |
) |
| 193 |
from ansible_collections.community.docker.plugins.plugin_utils._unsafe import ( |
| 194 |
make_unsafe, |
| 195 |
) |
| 196 |
|
| 197 |
if t.TYPE_CHECKING: |
| 198 |
from ansible.inventory.data import InventoryData |
| 199 |
from ansible.parsing.dataloader import DataLoader |
| 200 |
|
| 201 |
|
| 202 |
MIN_DOCKER_API = None |
| 203 |
|
| 204 |
|
| 205 |
class InventoryModule(BaseInventoryPlugin, Constructable): |
| 206 |
"""Host inventory parser for ansible using Docker daemon as source.""" |
| 207 |
|
| 208 |
NAME = "community.docker.docker_containers" |
| 209 |
|
| 210 |
def _slugify(self, value: str) -> str: |
| 211 |
slug = re.sub(r"[^\w-]", "_", value).lower().lstrip("_") |
| 212 |
return f"docker_{slug}" |
| 213 |
|
| 214 |
def _populate(self, client: AnsibleDockerClient) -> None: |
| 215 |
strict = self.get_option("strict") |
| 216 |
|
| 217 |
ssh_port = self.get_option("private_ssh_port") |
| 218 |
default_ip = self.get_option("default_ip") |
| 219 |
hostname = self.get_option("docker_host") |
| 220 |
verbose_output = self.get_option("verbose_output") |
| 221 |
connection_type = self.get_option("connection_type") |
| 222 |
add_legacy_groups = self.get_option("add_legacy_groups") |
| 223 |
|
| 224 |
if self.inventory is None: |
| 225 |
raise AssertionError("Inventory must be there") |
| 226 |
|
| 227 |
try: |
| 228 |
params = { |
| 229 |
"limit": -1, |
| 230 |
"all": 1, |
| 231 |
"size": 0, |
| 232 |
"trunc_cmd": 0, |
| 233 |
"since": None, |
| 234 |
"before": None, |
| 235 |
} |
| 236 |
containers = client.get_json("/containers/json", params=params) |
| 237 |
except APIError as exc: |
| 238 |
raise AnsibleError(f"Error listing containers: {exc}") from exc |
| 239 |
|
| 240 |
if add_legacy_groups: |
| 241 |
self.inventory.add_group("running") |
| 242 |
self.inventory.add_group("stopped") |
| 243 |
|
| 244 |
extra_facts = {} |
| 245 |
if self.get_option("configure_docker_daemon"): |
| 246 |
for option_name, var_name in DOCKER_COMMON_ARGS_VARS.items(): |
| 247 |
value = self.get_option(option_name) |
| 248 |
if value is not None: |
| 249 |
extra_facts[var_name] = value |
| 250 |
|
| 251 |
filters = parse_filters(self.get_option("filters")) |
| 252 |
for container in containers: |
| 253 |
container_id = container.get("Id") |
| 254 |
short_container_id = container_id[:13] |
| 255 |
|
| 256 |
try: |
| 257 |
name = container.get("Names", [])[0].lstrip("/") |
| 258 |
full_name = name |
| 259 |
except IndexError: |
| 260 |
name = short_container_id |
| 261 |
full_name = container_id |
| 262 |
|
| 263 |
facts = { |
| 264 |
"docker_name": make_unsafe(name), |
| 265 |
"docker_short_id": make_unsafe(short_container_id), |
| 266 |
} |
| 267 |
full_facts = {} |
| 268 |
|
| 269 |
try: |
| 270 |
inspect = client.get_json("/containers/{0}/json", container_id) |
| 271 |
except APIError as exc: |
| 272 |
raise AnsibleError( |
| 273 |
f"Error inspecting container {name} - {exc}" |
| 274 |
) from exc |
| 275 |
|
| 276 |
state = inspect.get("State") or {} |
| 277 |
config = inspect.get("Config") or {} |
| 278 |
labels = config.get("Labels") or {} |
| 279 |
|
| 280 |
running = state.get("Running") |
| 281 |
|
| 282 |
groups = [] |
| 283 |
|
| 284 |
# Add container to groups |
| 285 |
image_name = config.get("Image") |
| 286 |
if image_name and add_legacy_groups: |
| 287 |
groups.append(f"image_{image_name}") |
| 288 |
|
| 289 |
stack_name = labels.get("com.docker.stack.namespace") |
| 290 |
if stack_name: |
| 291 |
full_facts["docker_stack"] = stack_name |
| 292 |
if add_legacy_groups: |
| 293 |
groups.append(f"stack_{stack_name}") |
| 294 |
|
| 295 |
service_name = labels.get("com.docker.swarm.service.name") |
| 296 |
if service_name: |
| 297 |
full_facts["docker_service"] = service_name |
| 298 |
if add_legacy_groups: |
| 299 |
groups.append(f"service_{service_name}") |
| 300 |
|
| 301 |
ansible_connection = None |
| 302 |
if connection_type == "ssh": |
| 303 |
# Figure out ssh IP and Port |
| 304 |
try: |
| 305 |
# Lookup the public facing port Nat'ed to ssh port. |
| 306 |
network_settings = inspect.get("NetworkSettings") or {} |
| 307 |
port_settings = network_settings.get("Ports") or {} |
| 308 |
port = port_settings.get(f"{ssh_port}/tcp")[0] # type: ignore[index] |
| 309 |
except (IndexError, AttributeError, TypeError): |
| 310 |
port = {} |
| 311 |
|
| 312 |
try: |
| 313 |
ip = default_ip if port["HostIp"] == "0.0.0.0" else port["HostIp"] |
| 314 |
except KeyError: |
| 315 |
ip = "" |
| 316 |
|
| 317 |
facts.update( |
| 318 |
{ |
| 319 |
"ansible_ssh_host": ip, |
| 320 |
"ansible_ssh_port": port.get("HostPort", 0), |
| 321 |
} |
| 322 |
) |
| 323 |
elif connection_type == "docker-cli": |
| 324 |
facts.update( |
| 325 |
{ |
| 326 |
"ansible_host": full_name, |
| 327 |
} |
| 328 |
) |
| 329 |
ansible_connection = "community.docker.docker" |
| 330 |
elif connection_type == "docker-api": |
| 331 |
facts.update( |
| 332 |
{ |
| 333 |
"ansible_host": full_name, |
| 334 |
} |
| 335 |
) |
| 336 |
facts.update(extra_facts) |
| 337 |
ansible_connection = "community.docker.docker_api" |
| 338 |
|
| 339 |
full_facts.update(facts) |
| 340 |
for key, value in inspect.items(): |
| 341 |
fact_key = self._slugify(key) |
| 342 |
full_facts[fact_key] = value |
| 343 |
|
| 344 |
full_facts = make_unsafe(full_facts) |
| 345 |
|
| 346 |
if ansible_connection: |
| 347 |
for d in (facts, full_facts): |
| 348 |
if "ansible_connection" not in d: |
| 349 |
d["ansible_connection"] = ansible_connection |
| 350 |
|
| 351 |
if not filter_host(self, name, full_facts, filters): |
| 352 |
continue |
| 353 |
|
| 354 |
if verbose_output: |
| 355 |
facts.update(full_facts) |
| 356 |
|
| 357 |
self.inventory.add_host(name) |
| 358 |
for group in groups: |
| 359 |
self.inventory.add_group(group) |
| 360 |
self.inventory.add_host(name, group=group) |
| 361 |
|
| 362 |
for key, value in facts.items(): |
| 363 |
self.inventory.set_variable(name, key, value) |
| 364 |
|
| 365 |
# Use constructed if applicable |
| 366 |
# Composed variables |
| 367 |
self._set_composite_vars( |
| 368 |
self.get_option("compose"), full_facts, name, strict=strict |
| 369 |
) |
| 370 |
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group |
| 371 |
self._add_host_to_composed_groups( |
| 372 |
self.get_option("groups"), full_facts, name, strict=strict |
| 373 |
) |
| 374 |
# Create groups based on variable values and add the corresponding hosts to it |
| 375 |
self._add_host_to_keyed_groups( |
| 376 |
self.get_option("keyed_groups"), full_facts, name, strict=strict |
| 377 |
) |
| 378 |
|
| 379 |
# We need to do this last since we also add a group called `name`. |
| 380 |
# When we do this before a set_variable() call, the variables are assigned |
| 381 |
# to the group, and not to the host. |
| 382 |
if add_legacy_groups: |
| 383 |
self.inventory.add_group(container_id) |
| 384 |
self.inventory.add_host(name, group=container_id) |
| 385 |
self.inventory.add_group(name) |
| 386 |
self.inventory.add_host(name, group=name) |
| 387 |
self.inventory.add_group(short_container_id) |
| 388 |
self.inventory.add_host(name, group=short_container_id) |
| 389 |
self.inventory.add_group(hostname) |
| 390 |
self.inventory.add_host(name, group=hostname) |
| 391 |
|
| 392 |
if running is True: |
| 393 |
self.inventory.add_host(name, group="running") |
| 394 |
else: |
| 395 |
self.inventory.add_host(name, group="stopped") |
| 396 |
|
| 397 |
def verify_file(self, path: str) -> bool: |
| 398 |
"""Return the possibly of a file being consumable by this plugin.""" |
| 399 |
return super().verify_file(path) and path.endswith( |
| 400 |
("docker.yaml", "docker.yml") |
| 401 |
) |
| 402 |
|
| 403 |
def _create_client(self) -> AnsibleDockerClient: |
| 404 |
return AnsibleDockerClient(self, min_docker_api_version=MIN_DOCKER_API) |
| 405 |
|
| 406 |
def parse( |
| 407 |
self, |
| 408 |
inventory: InventoryData, |
| 409 |
loader: DataLoader, |
| 410 |
path: str, |
| 411 |
cache: bool = True, |
| 412 |
) -> None: |
| 413 |
super().parse(inventory, loader, path, cache) |
| 414 |
self._read_config_data(path) |
| 415 |
client = self._create_client() |
| 416 |
try: |
| 417 |
self._populate(client) |
| 418 |
except DockerException as e: |
| 419 |
raise AnsibleError(f"An unexpected Docker error occurred: {e}") from e |
| 420 |
except RequestException as e: |
| 421 |
raise AnsibleError( |
| 422 |
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}" |
| 423 |
) from e |