| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2019 Piotr Wojciechowski <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: docker_host_info |
| 11 |
|
| 12 |
short_description: Retrieves facts about docker host and lists of objects of the services |
| 13 |
|
| 14 |
description: |
| 15 |
- Retrieves facts about a docker host. |
| 16 |
- Essentially returns the output of C(docker system info). |
| 17 |
- The module also allows to list object names for containers, images, networks and volumes. It also allows to query information |
| 18 |
on disk usage. |
| 19 |
- The output differs depending on API version of the docker daemon. |
| 20 |
- If the docker daemon cannot be contacted or does not meet the API version requirements, the module will fail. |
| 21 |
extends_documentation_fragment: |
| 22 |
- community.docker._docker.api_documentation |
| 23 |
- community.docker._attributes |
| 24 |
- community.docker._attributes.actiongroup_docker |
| 25 |
- community.docker._attributes.idempotent_not_modify_state |
| 26 |
|
| 27 |
attributes: |
| 28 |
check_mode: |
| 29 |
support: full |
| 30 |
details: |
| 31 |
- This action does not modify state. |
| 32 |
diff_mode: |
| 33 |
support: N/A |
| 34 |
details: |
| 35 |
- This action does not modify state. |
| 36 |
|
| 37 |
options: |
| 38 |
containers: |
| 39 |
description: |
| 40 |
- Whether to list containers. |
| 41 |
type: bool |
| 42 |
default: false |
| 43 |
containers_all: |
| 44 |
description: |
| 45 |
- By default, only running containers are returned. |
| 46 |
- This corresponds to the C(--all) option to C(docker container list). |
| 47 |
type: bool |
| 48 |
default: false |
| 49 |
version_added: 3.4.0 |
| 50 |
containers_filters: |
| 51 |
description: |
| 52 |
- A dictionary of filter values used for selecting containers to list. |
| 53 |
- 'For example, C(until: 24h).' |
| 54 |
- C(label) is a special case of filter which can be a string C(<key>) matching when a label is present, a string C(<key>=<value>) |
| 55 |
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value). |
| 56 |
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/container_prune/#filtering) for |
| 57 |
more information on possible filters. |
| 58 |
type: dict |
| 59 |
images: |
| 60 |
description: |
| 61 |
- Whether to list images. |
| 62 |
type: bool |
| 63 |
default: false |
| 64 |
images_filters: |
| 65 |
description: |
| 66 |
- A dictionary of filter values used for selecting images to list. |
| 67 |
- 'For example, C(dangling: true).' |
| 68 |
- C(label) is a special case of filter which can be a string C(<key>) matching when a label is present, a string C(<key>=<value>) |
| 69 |
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value). |
| 70 |
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/image_prune/#filtering) for more |
| 71 |
information on possible filters. |
| 72 |
type: dict |
| 73 |
networks: |
| 74 |
description: |
| 75 |
- Whether to list networks. |
| 76 |
type: bool |
| 77 |
default: false |
| 78 |
networks_filters: |
| 79 |
description: |
| 80 |
- A dictionary of filter values used for selecting networks to list. |
| 81 |
- C(label) is a special case of filter which can be a string C(<key>) matching when a label is present, a string C(<key>=<value>) |
| 82 |
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value). |
| 83 |
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/network_prune/#filtering) for |
| 84 |
more information on possible filters. |
| 85 |
type: dict |
| 86 |
volumes: |
| 87 |
description: |
| 88 |
- Whether to list volumes. |
| 89 |
type: bool |
| 90 |
default: false |
| 91 |
volumes_filters: |
| 92 |
description: |
| 93 |
- A dictionary of filter values used for selecting volumes to list. |
| 94 |
- C(label) is a special case of filter which can be a string C(<key>) matching when a label is present, a string C(<key>=<value>) |
| 95 |
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value). |
| 96 |
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/volume_prune/#filtering) for more |
| 97 |
information on possible filters. |
| 98 |
type: dict |
| 99 |
disk_usage: |
| 100 |
description: |
| 101 |
- Summary information on used disk space by all Docker layers. |
| 102 |
- The output is a sum of images, volumes, containers and build cache. |
| 103 |
type: bool |
| 104 |
default: false |
| 105 |
verbose_output: |
| 106 |
description: |
| 107 |
- When set to V(true) and O(networks), O(volumes), O(images), O(containers), or O(disk_usage) is set to V(true) then |
| 108 |
output will contain verbose information about objects matching the full output of API method. For details see the |
| 109 |
documentation of your version of Docker API at U(https://docs.docker.com/engine/api/). |
| 110 |
- The verbose output in this module contains only subset of information returned by this module for each type of the |
| 111 |
objects. |
| 112 |
type: bool |
| 113 |
default: false |
| 114 |
|
| 115 |
author: |
| 116 |
- Piotr Wojciechowski (@WojciechowskiPiotr) |
| 117 |
|
| 118 |
requirements: |
| 119 |
- "Docker API >= 1.25" |
| 120 |
""" |
| 121 |
|
| 122 |
EXAMPLES = r""" |
| 123 |
--- |
| 124 |
- name: Get info on docker host |
| 125 |
community.docker.docker_host_info: |
| 126 |
register: result |
| 127 |
|
| 128 |
- name: Get info on docker host and list images |
| 129 |
community.docker.docker_host_info: |
| 130 |
images: true |
| 131 |
register: result |
| 132 |
|
| 133 |
- name: Get info on docker host and list images matching the filter |
| 134 |
community.docker.docker_host_info: |
| 135 |
images: true |
| 136 |
images_filters: |
| 137 |
label: "mylabel" |
| 138 |
register: result |
| 139 |
|
| 140 |
- name: Get info on docker host and verbose list images |
| 141 |
community.docker.docker_host_info: |
| 142 |
images: true |
| 143 |
verbose_output: true |
| 144 |
register: result |
| 145 |
|
| 146 |
- name: Get info on docker host and used disk space |
| 147 |
community.docker.docker_host_info: |
| 148 |
disk_usage: true |
| 149 |
register: result |
| 150 |
|
| 151 |
- name: Get info on docker host and list containers matching the filter |
| 152 |
community.docker.docker_host_info: |
| 153 |
containers: true |
| 154 |
containers_filters: |
| 155 |
label: |
| 156 |
- key1=value1 |
| 157 |
- key2=value2 |
| 158 |
register: result |
| 159 |
|
| 160 |
- name: Show host information |
| 161 |
ansible.builtin.debug: |
| 162 |
var: result.host_info |
| 163 |
""" |
| 164 |
|
| 165 |
RETURN = r""" |
| 166 |
can_talk_to_docker: |
| 167 |
description: |
| 168 |
- Will be V(true) if the module can talk to the docker daemon. |
| 169 |
returned: both on success and on error |
| 170 |
type: bool |
| 171 |
|
| 172 |
host_info: |
| 173 |
description: |
| 174 |
- Facts representing the basic state of the docker host. Matches the C(docker system info) output. |
| 175 |
returned: always |
| 176 |
type: dict |
| 177 |
volumes: |
| 178 |
description: |
| 179 |
- List of dict objects containing the basic information about each volume. Keys matches the C(docker volume ls) output |
| 180 |
unless O(verbose_output=true). See description for O(verbose_output). |
| 181 |
returned: When O(volumes=true) |
| 182 |
type: list |
| 183 |
elements: dict |
| 184 |
networks: |
| 185 |
description: |
| 186 |
- List of dict objects containing the basic information about each network. Keys matches the C(docker network ls) output |
| 187 |
unless O(verbose_output=true). See description for O(verbose_output). |
| 188 |
returned: When O(networks=true) |
| 189 |
type: list |
| 190 |
elements: dict |
| 191 |
containers: |
| 192 |
description: |
| 193 |
- List of dict objects containing the basic information about each container. Keys matches the C(docker container ls) |
| 194 |
output unless O(verbose_output=true). See description for O(verbose_output). |
| 195 |
returned: When O(containers=true) |
| 196 |
type: list |
| 197 |
elements: dict |
| 198 |
images: |
| 199 |
description: |
| 200 |
- List of dict objects containing the basic information about each image. Keys matches the C(docker image ls) output unless |
| 201 |
O(verbose_output=true). See description for O(verbose_output). |
| 202 |
returned: When O(images=true) |
| 203 |
type: list |
| 204 |
elements: dict |
| 205 |
disk_usage: |
| 206 |
description: |
| 207 |
- Information on summary disk usage by images, containers and volumes on docker host unless O(verbose_output=true). See |
| 208 |
description for O(verbose_output). |
| 209 |
returned: When O(disk_usage=true) |
| 210 |
type: dict |
| 211 |
""" |
| 212 |
|
| 213 |
import traceback |
| 214 |
import typing as t |
| 215 |
|
| 216 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 217 |
APIError, |
| 218 |
DockerException, |
| 219 |
) |
| 220 |
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import ( |
| 221 |
convert_filters, |
| 222 |
) |
| 223 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 224 |
AnsibleDockerClient, |
| 225 |
RequestException, |
| 226 |
) |
| 227 |
from ansible_collections.community.docker.plugins.module_utils._util import ( |
| 228 |
DockerBaseClass, |
| 229 |
clean_dict_booleans_for_docker_api, |
| 230 |
) |
| 231 |
|
| 232 |
|
| 233 |
class DockerHostManager(DockerBaseClass): |
| 234 |
def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None: |
| 235 |
super().__init__() |
| 236 |
|
| 237 |
self.client = client |
| 238 |
self.results = results |
| 239 |
self.verbose_output = self.client.module.params["verbose_output"] |
| 240 |
|
| 241 |
listed_objects = ["volumes", "networks", "containers", "images"] |
| 242 |
|
| 243 |
self.results["host_info"] = self.get_docker_host_info() |
| 244 |
# At this point we definitely know that we can talk to the Docker daemon |
| 245 |
self.results["can_talk_to_docker"] = True |
| 246 |
self.client.fail_results["can_talk_to_docker"] = True |
| 247 |
|
| 248 |
if self.client.module.params["disk_usage"]: |
| 249 |
self.results["disk_usage"] = self.get_docker_disk_usage_facts() |
| 250 |
|
| 251 |
for docker_object in listed_objects: |
| 252 |
if self.client.module.params[docker_object]: |
| 253 |
returned_name = docker_object |
| 254 |
filter_name = f"{docker_object}_filters" |
| 255 |
filters = clean_dict_booleans_for_docker_api( |
| 256 |
client.module.params.get(filter_name), allow_sequences=True |
| 257 |
) |
| 258 |
self.results[returned_name] = self.get_docker_items_list( |
| 259 |
docker_object, filters |
| 260 |
) |
| 261 |
|
| 262 |
def get_docker_host_info(self) -> dict[str, t.Any]: |
| 263 |
try: |
| 264 |
return self.client.info() |
| 265 |
except APIError as exc: |
| 266 |
self.client.fail(f"Error inspecting docker host: {exc}") |
| 267 |
|
| 268 |
def get_docker_disk_usage_facts(self) -> dict[str, t.Any]: |
| 269 |
try: |
| 270 |
if self.verbose_output: |
| 271 |
return self.client.df() |
| 272 |
return {"LayersSize": self.client.df()["LayersSize"]} |
| 273 |
except APIError as exc: |
| 274 |
self.client.fail(f"Error inspecting docker host: {exc}") |
| 275 |
|
| 276 |
def get_docker_items_list( |
| 277 |
self, |
| 278 |
docker_object: str, |
| 279 |
filters: dict[str, t.Any] | None = None, |
| 280 |
verbose: bool = False, |
| 281 |
) -> list[dict[str, t.Any]]: |
| 282 |
items = [] |
| 283 |
|
| 284 |
header_containers = [ |
| 285 |
"Id", |
| 286 |
"Image", |
| 287 |
"Command", |
| 288 |
"Created", |
| 289 |
"Status", |
| 290 |
"Ports", |
| 291 |
"Names", |
| 292 |
] |
| 293 |
header_volumes = ["Driver", "Name"] |
| 294 |
header_images = ["Id", "RepoTags", "Created", "Size"] |
| 295 |
header_networks = ["Id", "Driver", "Name", "Scope"] |
| 296 |
|
| 297 |
filter_arg = {} |
| 298 |
if filters: |
| 299 |
filter_arg["filters"] = filters |
| 300 |
try: |
| 301 |
if docker_object == "containers": |
| 302 |
params = { |
| 303 |
"limit": -1, |
| 304 |
"all": 1 if self.client.module.params["containers_all"] else 0, |
| 305 |
"size": 0, |
| 306 |
"trunc_cmd": 0, |
| 307 |
"filters": convert_filters(filters) if filters else None, |
| 308 |
} |
| 309 |
items = self.client.get_json("/containers/json", params=params) |
| 310 |
elif docker_object == "networks": |
| 311 |
params = {"filters": convert_filters(filters or {})} |
| 312 |
items = self.client.get_json("/networks", params=params) |
| 313 |
elif docker_object == "images": |
| 314 |
params = { |
| 315 |
"only_ids": 0, |
| 316 |
"all": 0, |
| 317 |
"filters": convert_filters(filters) if filters else None, |
| 318 |
} |
| 319 |
items = self.client.get_json("/images/json", params=params) |
| 320 |
elif docker_object == "volumes": |
| 321 |
params = { |
| 322 |
"filters": convert_filters(filters) if filters else None, |
| 323 |
} |
| 324 |
items = self.client.get_json("/volumes", params=params) |
| 325 |
items = items["Volumes"] |
| 326 |
except APIError as exc: |
| 327 |
self.client.fail( |
| 328 |
f"Error inspecting docker host for object '{docker_object}': {exc}" |
| 329 |
) |
| 330 |
|
| 331 |
if self.verbose_output: |
| 332 |
return items |
| 333 |
|
| 334 |
items_list = [] |
| 335 |
for item in items: |
| 336 |
item_record = {} |
| 337 |
|
| 338 |
if docker_object == "containers": |
| 339 |
for key in header_containers: |
| 340 |
item_record[key] = item.get(key) |
| 341 |
elif docker_object == "networks": |
| 342 |
for key in header_networks: |
| 343 |
item_record[key] = item.get(key) |
| 344 |
elif docker_object == "images": |
| 345 |
for key in header_images: |
| 346 |
item_record[key] = item.get(key) |
| 347 |
elif docker_object == "volumes": |
| 348 |
for key in header_volumes: |
| 349 |
item_record[key] = item.get(key) |
| 350 |
items_list.append(item_record) |
| 351 |
|
| 352 |
return items_list |
| 353 |
|
| 354 |
|
| 355 |
def main() -> None: |
| 356 |
argument_spec = { |
| 357 |
"containers": {"type": "bool", "default": False}, |
| 358 |
"containers_all": {"type": "bool", "default": False}, |
| 359 |
"containers_filters": {"type": "dict"}, |
| 360 |
"images": {"type": "bool", "default": False}, |
| 361 |
"images_filters": {"type": "dict"}, |
| 362 |
"networks": {"type": "bool", "default": False}, |
| 363 |
"networks_filters": {"type": "dict"}, |
| 364 |
"volumes": {"type": "bool", "default": False}, |
| 365 |
"volumes_filters": {"type": "dict"}, |
| 366 |
"disk_usage": {"type": "bool", "default": False}, |
| 367 |
"verbose_output": {"type": "bool", "default": False}, |
| 368 |
} |
| 369 |
|
| 370 |
client = AnsibleDockerClient( |
| 371 |
argument_spec=argument_spec, |
| 372 |
supports_check_mode=True, |
| 373 |
fail_results={ |
| 374 |
"can_talk_to_docker": False, |
| 375 |
}, |
| 376 |
) |
| 377 |
if ( |
| 378 |
client.module.params["api_version"] is None |
| 379 |
or client.module.params["api_version"].lower() == "auto" |
| 380 |
): |
| 381 |
# At this point we know that we can talk to Docker, since we asked it for the API version |
| 382 |
client.fail_results["can_talk_to_docker"] = True |
| 383 |
|
| 384 |
try: |
| 385 |
results = { |
| 386 |
"changed": False, |
| 387 |
} |
| 388 |
|
| 389 |
DockerHostManager(client, results) |
| 390 |
client.module.exit_json(**results) |
| 391 |
except DockerException as e: |
| 392 |
client.fail( |
| 393 |
f"An unexpected Docker error occurred: {e}", |
| 394 |
exception=traceback.format_exc(), |
| 395 |
) |
| 396 |
except RequestException as e: |
| 397 |
client.fail( |
| 398 |
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}", |
| 399 |
exception=traceback.format_exc(), |
| 400 |
) |
| 401 |
|
| 402 |
|
| 403 |
if __name__ == "__main__": |
| 404 |
main() |