Vendor Galaxy Roles and Collections

This commit is contained in:
Stefan Bethke 2026-02-06 22:07:16 +01:00
commit 2aed20393f
38 changed files with 387444 additions and 2 deletions

View file

@ -0,0 +1,148 @@
#!/usr/bin/python
#
# Copyright (c) 2020 Matt Clay <mclay@redhat.com>
# Copyright (c) 2020 Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: current_container_facts
short_description: Return facts about whether the module runs in a container
version_added: 1.1.0
description:
- Return facts about whether the module runs in a Docker or podman container.
- This module attempts a best-effort detection. There might be special cases where it does not work; if you encounter one,
make sure that this is still a problem with the latest community.docker release, and if it is,
L(please file an issue, https://github.com/ansible-collections/community.docker/issues/new?assignees=&labels=&template=bug_report.md).
author:
- Felix Fontein (@felixfontein)
extends_documentation_fragment:
- community.docker._attributes
- community.docker._attributes.facts
- community.docker._attributes.facts_module
- community.docker._attributes.idempotent_not_modify_state
"""
EXAMPLES = r"""
---
- name: Get facts on current container
community.docker.current_container_facts:
- name: Print information on current container when running in a container
ansible.builtin.debug:
msg: "Container ID is {{ ansible_module_container_id }}"
when: ansible_module_running_in_container
"""
RETURN = r"""
ansible_facts:
description: Ansible facts returned by the module.
type: dict
returned: always
contains:
ansible_module_running_in_container:
description:
- Whether the module was able to detect that it runs in a container or not.
returned: always
type: bool
ansible_module_container_id:
description:
- The detected container ID.
- Contains an empty string if no container was detected.
returned: always
type: str
ansible_module_container_type:
description:
- The detected container environment.
- Contains an empty string if no container was detected, or a non-empty string identifying the container environment.
- V(docker) indicates that the module ran inside a regular Docker container.
- V(azure_pipelines) indicates that the module ran on Azure Pipelines. This seems to no longer be reported.
- V(github_actions) indicates that the module ran inside a Docker container on GitHub Actions. It is supported since
community.docker 2.4.0.
- V(podman) indicates that the module ran inside a regular Podman container. It is supported since community.docker
3.3.0.
returned: always
type: str
choices:
- ''
- docker
- azure_pipelines
- github_actions
- podman
"""
import os
import re
from ansible.module_utils.basic import AnsibleModule
def main() -> None:
module = AnsibleModule({}, supports_check_mode=True)
cpuset_path = "/proc/self/cpuset"
mountinfo_path = "/proc/self/mountinfo"
container_id = ""
container_type = ""
contents = None
if os.path.exists(cpuset_path):
# File content varies based on the environment:
# No Container: /
# Docker: /docker/c86f3732b5ba3d28bb83b6e14af767ab96abbc52de31313dcb1176a62d91a507
# Azure Pipelines (Docker): /azpl_job/0f2edfed602dd6ec9f2e42c867f4d5ee640ebf4c058e6d3196d4393bb8fd0891
# Podman: /../../../../../..
# While this was true and worked well for a long time, this seems to be no longer accurate
# with newer Docker / Podman versions and/or with cgroupv2. That's why the /proc/self/mountinfo
# detection further down is done when this test is inconclusive.
with open(cpuset_path, "rb") as f:
contents = f.read().decode("utf-8")
cgroup_path, cgroup_name = os.path.split(contents.strip())
if cgroup_path == "/docker":
container_id = cgroup_name
container_type = "docker"
if cgroup_path == "/azpl_job":
container_id = cgroup_name
container_type = "azure_pipelines"
if cgroup_path == "/actions_job":
container_id = cgroup_name
container_type = "github_actions"
if not container_id and os.path.exists(mountinfo_path):
with open(mountinfo_path, "rb") as f:
contents = f.read().decode("utf-8")
# As to why this works, see the explanations by Matt Clay in
# https://github.com/ansible/ansible/blob/80d2f8da02052f64396da6b8caaf820eedbf18e2/test/lib/ansible_test/_internal/docker_util.py#L571-L610
for line in contents.splitlines():
parts = line.split()
if len(parts) >= 5 and parts[4] == "/etc/hostname":
m = re.match(".*/([a-f0-9]{64})/hostname$", parts[3])
if m:
container_id = m.group(1)
container_type = "docker"
m = re.match(".*/([a-f0-9]{64})/userdata/hostname$", parts[3])
if m:
container_id = m.group(1)
container_type = "podman"
module.exit_json(
ansible_facts={
"ansible_module_running_in_container": container_id != "",
"ansible_module_container_id": container_id,
"ansible_module_container_type": container_type,
}
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,748 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# Copyright (c) 2023, Léo El Amri (@lel-amri)
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_compose_v2
short_description: Manage multi-container Docker applications with Docker Compose CLI plugin
version_added: 3.6.0
description:
- Uses Docker Compose to start or shutdown services.
extends_documentation_fragment:
- community.docker._compose_v2
- community.docker._compose_v2.minimum_version
- community.docker._docker.cli_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: full
details:
- In check mode, pulling the image does not result in a changed result.
diff_mode:
support: none
idempotent:
support: partial
details:
- If O(state=restarted) or O(recreate=always) the module is not idempotent.
options:
state:
description:
- Desired state of the project.
- V(present) is equivalent to running C(docker compose up).
- V(stopped) is equivalent to running C(docker compose stop).
- V(absent) is equivalent to running C(docker compose down).
- V(restarted) is equivalent to running C(docker compose restart).
type: str
default: present
choices:
- absent
- stopped
- restarted
- present
pull:
description:
- Whether to pull images before running. This is used when C(docker compose up) is run.
- V(always) ensures that the images are always pulled, even when already present on the Docker daemon.
- V(missing) only pulls them when they are not present on the Docker daemon.
- V(never) never pulls images. If they are not present, the module will fail when trying to create the containers that
need them.
- V(policy) use the Compose file's C(pull_policy) defined for the service to figure out what to do.
type: str
choices:
- always
- missing
- never
- policy
default: policy
build:
description:
- Whether to build images before starting containers. This is used when C(docker compose up) is run.
- V(always) always builds before starting containers. This is equivalent to the C(--build) option of C(docker compose
up).
- V(never) never builds before starting containers. This is equivalent to the C(--no-build) option of C(docker compose
up).
- V(policy) uses the policy as defined in the Compose file.
type: str
choices:
- always
- never
- policy
default: policy
dependencies:
description:
- When O(state) is V(present) or V(restarted), specify whether or not to include linked services.
type: bool
default: true
ignore_build_events:
description:
- Ignores image building events for change detection.
- If O(state=present) and O(ignore_build_events=true) and O(build=always), a rebuild that does not trigger a container
restart no longer results in RV(ignore:changed=true).
- Note that Docker Compose 2.31.0 is the first Compose 2.x version to emit build events. For older versions, the behavior
is always as if O(ignore_build_events=true).
type: bool
default: true
version_added: 4.2.0
recreate:
description:
- By default containers will be recreated when their configuration differs from the service definition.
- Setting to V(never) ignores configuration differences and leaves existing containers unchanged.
- Setting to V(always) forces recreation of all existing containers.
type: str
default: auto
choices:
- always
- never
- auto
renew_anon_volumes:
description:
- Whether to recreate instead of reuse anonymous volumes from previous containers.
- V(true) is equivalent to the C(--renew-anon-volumes) option of C(docker compose up).
type: bool
default: false
version_added: 4.0.0
remove_images:
description:
- Use with O(state=absent) to remove all images or only local images.
type: str
choices:
- all
- local
remove_volumes:
description:
- Use with O(state=absent) to remove data volumes.
type: bool
default: false
remove_orphans:
description:
- Remove containers for services not defined in the Compose file.
type: bool
default: false
timeout:
description:
- Timeout in seconds for container shutdown when attached or when containers are already running.
type: int
services:
description:
- Specifies a subset of services to be targeted.
type: list
elements: str
scale:
description:
- Define how to scale services when running C(docker compose up).
- Provide a dictionary of key/value pairs where the key is the name of the service and the value is an integer count
for the number of containers.
type: dict
version_added: 3.7.0
wait:
description:
- When running C(docker compose up), pass C(--wait) to wait for services to be running/healthy.
- A timeout can be set with the O(wait_timeout) option.
type: bool
default: false
version_added: 3.8.0
wait_timeout:
description:
- When O(wait=true), wait at most this amount of seconds.
type: int
version_added: 3.8.0
assume_yes:
description:
- When O(assume_yes=true), pass C(-y)/C(--yes) to assume "yes" as answer to all prompts and run non-interactively.
- Right now a prompt is asked whenever a non-matching volume should be re-created. O(assume_yes=false)
results in the question being answered by "no", which will simply re-use the existing volume.
- This option is only available on Docker Compose 2.32.0 or newer.
type: bool
default: false
version_added: 4.5.0
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_compose_v2_pull
"""
EXAMPLES = r"""
---
# Examples use the django example at https://docs.docker.com/compose/django. Follow it to create the
# flask directory
- name: Run using a project directory
hosts: localhost
gather_facts: false
tasks:
- name: Tear down existing services
community.docker.docker_compose_v2:
project_src: flask
state: absent
- name: Create and start services
community.docker.docker_compose_v2:
project_src: flask
register: output
- name: Show results
ansible.builtin.debug:
var: output
- name: Run `docker compose up` again
community.docker.docker_compose_v2:
project_src: flask
register: output
- name: Show results
ansible.builtin.debug:
var: output
- ansible.builtin.assert:
that: not output.changed
- name: Stop all services
community.docker.docker_compose_v2:
project_src: flask
state: stopped
register: output
- name: Show results
ansible.builtin.debug:
var: output
- name: Verify that web and db services are not running
ansible.builtin.assert:
that:
- web_container.State != 'running'
- db_container.State != 'running'
vars:
web_container: >-
{{ output.containers | selectattr("Service", "equalto", "web") | first }}
db_container: >-
{{ output.containers | selectattr("Service", "equalto", "db") | first }}
- name: Restart services
community.docker.docker_compose_v2:
project_src: flask
state: restarted
register: output
- name: Show results
ansible.builtin.debug:
var: output
- name: Verify that web and db services are running
ansible.builtin.assert:
that:
- web_container.State == 'running'
- db_container.State == 'running'
vars:
web_container: >-
{{ output.containers | selectattr("Service", "equalto", "web") | first }}
db_container: >-
{{ output.containers | selectattr("Service", "equalto", "db") | first }}
"""
RETURN = r"""
containers:
description:
- A list of containers associated to the service.
returned: success
type: list
elements: dict
contains:
Command:
description:
- The container's command.
type: raw
CreatedAt:
description:
- The timestamp when the container was created.
type: str
sample: "2024-01-02 12:20:41 +0100 CET"
ExitCode:
description:
- The container's exit code.
type: int
Health:
description:
- The container's health check.
type: raw
ID:
description:
- The container's ID.
type: str
sample: "44a7d607219a60b7db0a4817fb3205dce46e91df2cb4b78a6100b6e27b0d3135"
Image:
description:
- The container's image.
type: str
Labels:
description:
- Labels for this container.
type: dict
LocalVolumes:
description:
- The local volumes count.
type: str
Mounts:
description:
- Mounts.
type: str
Name:
description:
- The container's primary name.
type: str
Names:
description:
- List of names of the container.
type: list
elements: str
Networks:
description:
- List of networks attached to this container.
type: list
elements: str
Ports:
description:
- List of port assignments as a string.
type: str
Publishers:
description:
- List of port assigments.
type: list
elements: dict
contains:
URL:
description:
- Interface the port is bound to.
type: str
TargetPort:
description:
- The container's port the published port maps to.
type: int
PublishedPort:
description:
- The port that is published.
type: int
Protocol:
description:
- The protocol.
type: str
choices:
- tcp
- udp
RunningFor:
description:
- Amount of time the container runs.
type: str
Service:
description:
- The name of the service.
type: str
Size:
description:
- The container's size.
type: str
sample: "0B"
State:
description:
- The container's state.
type: str
sample: running
Status:
description:
- The container's status.
type: str
sample: Up About a minute
images:
description:
- A list of images associated to the service.
returned: success
type: list
elements: dict
contains:
ID:
description:
- The image's ID.
type: str
sample: sha256:c8bccc0af9571ec0d006a43acb5a8d08c4ce42b6cc7194dd6eb167976f501ef1
ContainerName:
description:
- Name of the conainer this image is used by.
type: str
Repository:
description:
- The repository where this image belongs to.
type: str
Tag:
description:
- The tag of the image.
type: str
Size:
description:
- The image's size in bytes.
type: int
actions:
description:
- A list of actions that have been applied.
returned: success
type: list
elements: dict
contains:
what:
description:
- What kind of resource was changed.
type: str
sample: container
choices:
- container
- image
- network
- service
- unknown
- volume
id:
description:
- The ID of the resource that was changed.
type: str
sample: container
status:
description:
- The status change that happened.
type: str
sample: Creating
choices:
- Starting
- Exiting
- Restarting
- Creating
- Stopping
- Killing
- Removing
- Recreating
- Pulling
- Building
"""
import traceback
import typing as t
from ansible.module_utils.common.validation import check_type_int
from ansible_collections.community.docker.plugins.module_utils._common_cli import (
AnsibleModuleDockerClient,
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._compose_v2 import (
BaseComposeManager,
common_compose_argspec_ex,
is_failed,
)
from ansible_collections.community.docker.plugins.module_utils._version import (
LooseVersion,
)
class ServicesManager(BaseComposeManager):
def __init__(self, client: AnsibleModuleDockerClient) -> None:
super().__init__(client)
parameters = self.client.module.params
self.state: t.Literal["absent", "present", "stopped", "restarted"] = parameters[
"state"
]
self.dependencies: bool = parameters["dependencies"]
self.pull: t.Literal["always", "missing", "never", "policy"] = parameters[
"pull"
]
self.build: t.Literal["always", "never", "policy"] = parameters["build"]
self.ignore_build_events: bool = parameters["ignore_build_events"]
self.recreate: t.Literal["always", "never", "auto"] = parameters["recreate"]
self.remove_images: t.Literal["all", "local"] | None = parameters[
"remove_images"
]
self.remove_volumes: bool = parameters["remove_volumes"]
self.remove_orphans: bool = parameters["remove_orphans"]
self.renew_anon_volumes: bool = parameters["renew_anon_volumes"]
self.timeout: int | None = parameters["timeout"]
self.services: list[str] = parameters["services"] or []
self.scale: dict[str, t.Any] = parameters["scale"] or {}
self.wait: bool = parameters["wait"]
self.wait_timeout: int | None = parameters["wait_timeout"]
self.yes: bool = parameters["assume_yes"]
if self.compose_version < LooseVersion("2.32.0") and self.yes:
self.fail(
f"assume_yes=true needs Docker Compose 2.32.0 or newer, not version {self.compose_version}"
)
for key, value in self.scale.items():
if not isinstance(key, str):
self.fail(f"The key {key!r} for `scale` is not a string")
try:
value = check_type_int(value)
except TypeError:
self.fail(f"The value {value!r} for `scale[{key!r}]` is not an integer")
if value < 0:
self.fail(f"The value {value!r} for `scale[{key!r}]` is negative")
self.scale[key] = value
def run(self) -> dict[str, t.Any]:
if self.state == "present":
result = self.cmd_up()
elif self.state == "stopped":
result = self.cmd_stop()
elif self.state == "restarted":
result = self.cmd_restart()
elif self.state == "absent":
result = self.cmd_down()
else:
raise AssertionError("Unexpected state")
result["containers"] = self.list_containers()
result["images"] = self.list_images()
self.cleanup_result(result)
return result
def get_up_cmd(self, dry_run: bool, no_start: bool = False) -> list[str]:
args = self.get_base_args() + ["up", "--detach", "--no-color", "--quiet-pull"]
if self.pull != "policy":
args.extend(["--pull", self.pull])
if self.remove_orphans:
args.append("--remove-orphans")
if self.recreate == "always":
args.append("--force-recreate")
if self.recreate == "never":
args.append("--no-recreate")
if self.renew_anon_volumes:
args.append("--renew-anon-volumes")
if not self.dependencies:
args.append("--no-deps")
if self.timeout is not None:
args.extend(["--timeout", f"{self.timeout}"])
if self.build == "always":
args.append("--build")
elif self.build == "never":
args.append("--no-build")
for key, value in sorted(self.scale.items()):
args.extend(["--scale", f"{key}={value}"])
if self.wait:
args.append("--wait")
if self.wait_timeout is not None:
args.extend(["--wait-timeout", str(self.wait_timeout)])
if no_start:
args.append("--no-start")
if dry_run:
args.append("--dry-run")
if self.yes:
# Note that for Docker Compose 2.32.x and 2.33.x, the long form is '--y' and not '--yes'.
# This was fixed in Docker Compose 2.34.0 (https://github.com/docker/compose/releases/tag/v2.34.0).
args.append(
"-y" if self.compose_version < LooseVersion("2.34.0") else "--yes"
)
args.append("--")
for service in self.services:
args.append(service)
return args
def cmd_up(self) -> dict[str, t.Any]:
result: dict[str, t.Any] = {}
args = self.get_up_cmd(self.check_mode)
rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
self.emit_warnings(events)
self.update_result(
result,
events,
stdout,
stderr,
ignore_service_pull_events=True,
ignore_build_events=self.ignore_build_events,
)
self.update_failed(result, events, args, stdout, stderr, rc)
return result
def get_stop_cmd(self, dry_run: bool) -> list[str]:
args = self.get_base_args() + ["stop"]
if self.timeout is not None:
args.extend(["--timeout", f"{self.timeout}"])
if dry_run:
args.append("--dry-run")
args.append("--")
for service in self.services:
args.append(service)
return args
def _are_containers_stopped(self) -> bool:
return all(
container["State"] in ("created", "exited", "stopped", "killed")
for container in self.list_containers_raw()
)
def cmd_stop(self) -> dict[str, t.Any]:
# Since 'docker compose stop' **always** claims it is stopping containers, even if they are already
# stopped, we have to do this a bit more complicated.
result: dict[str, t.Any] = {}
# Make sure all containers are created
args_1 = self.get_up_cmd(self.check_mode, no_start=True)
rc_1, stdout_1, stderr_1 = self.client.call_cli(*args_1, cwd=self.project_src)
events_1 = self.parse_events(
stderr_1, dry_run=self.check_mode, nonzero_rc=rc_1 != 0
)
self.emit_warnings(events_1)
self.update_result(
result,
events_1,
stdout_1,
stderr_1,
ignore_service_pull_events=True,
ignore_build_events=self.ignore_build_events,
)
is_failed_1 = is_failed(events_1, rc_1)
if not is_failed_1 and not self._are_containers_stopped():
# Make sure all containers are stopped
args_2 = self.get_stop_cmd(self.check_mode)
rc_2, stdout_2, stderr_2 = self.client.call_cli(
*args_2, cwd=self.project_src
)
events_2 = self.parse_events(
stderr_2, dry_run=self.check_mode, nonzero_rc=rc_2 != 0
)
self.emit_warnings(events_2)
self.update_result(result, events_2, stdout_2, stderr_2)
else:
args_2 = []
rc_2, stdout_2, stderr_2 = 0, b"", b""
events_2 = []
# Compose result
self.update_failed(
result,
events_1 + events_2,
args_1 if is_failed_1 else args_2,
stdout_1 if is_failed_1 else stdout_2,
stderr_1 if is_failed_1 else stderr_2,
rc_1 if is_failed_1 else rc_2,
)
return result
def get_restart_cmd(self, dry_run: bool) -> list[str]:
args = self.get_base_args() + ["restart"]
if not self.dependencies:
args.append("--no-deps")
if self.timeout is not None:
args.extend(["--timeout", f"{self.timeout}"])
if dry_run:
args.append("--dry-run")
args.append("--")
for service in self.services:
args.append(service)
return args
def cmd_restart(self) -> dict[str, t.Any]:
result: dict[str, t.Any] = {}
args = self.get_restart_cmd(self.check_mode)
rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
self.emit_warnings(events)
self.update_result(result, events, stdout, stderr)
self.update_failed(result, events, args, stdout, stderr, rc)
return result
def get_down_cmd(self, dry_run: bool) -> list[str]:
args = self.get_base_args() + ["down"]
if self.remove_orphans:
args.append("--remove-orphans")
if self.remove_images:
args.extend(["--rmi", self.remove_images])
if self.remove_volumes:
args.append("--volumes")
if self.timeout is not None:
args.extend(["--timeout", f"{self.timeout}"])
if dry_run:
args.append("--dry-run")
args.append("--")
for service in self.services:
args.append(service)
return args
def cmd_down(self) -> dict[str, t.Any]:
result: dict[str, t.Any] = {}
args = self.get_down_cmd(self.check_mode)
rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
self.emit_warnings(events)
self.update_result(result, events, stdout, stderr)
self.update_failed(result, events, args, stdout, stderr, rc)
return result
def main() -> None:
argument_spec = {
"state": {
"type": "str",
"default": "present",
"choices": ["absent", "present", "stopped", "restarted"],
},
"dependencies": {"type": "bool", "default": True},
"pull": {
"type": "str",
"choices": ["always", "missing", "never", "policy"],
"default": "policy",
},
"build": {
"type": "str",
"choices": ["always", "never", "policy"],
"default": "policy",
},
"recreate": {
"type": "str",
"default": "auto",
"choices": ["always", "never", "auto"],
},
"renew_anon_volumes": {"type": "bool", "default": False},
"remove_images": {"type": "str", "choices": ["all", "local"]},
"remove_volumes": {"type": "bool", "default": False},
"remove_orphans": {"type": "bool", "default": False},
"timeout": {"type": "int"},
"services": {"type": "list", "elements": "str"},
"scale": {"type": "dict"},
"wait": {"type": "bool", "default": False},
"wait_timeout": {"type": "int"},
"ignore_build_events": {"type": "bool", "default": True},
"assume_yes": {"type": "bool", "default": False},
}
argspec_ex = common_compose_argspec_ex()
argument_spec.update(argspec_ex.pop("argspec"))
client = AnsibleModuleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
needs_api_version=False,
**argspec_ex,
)
try:
manager = ServicesManager(client)
result = manager.run()
manager.cleanup()
client.module.exit_json(**result)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,308 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_compose_v2_exec
short_description: Run command in a container of a Compose service
version_added: 3.13.0
description:
- Uses Docker Compose to run a command in a service's container.
- This can be used to run one-off commands in an existing service's container, and encapsulates C(docker compose exec).
extends_documentation_fragment:
- community.docker._compose_v2
- community.docker._compose_v2.minimum_version
- community.docker._docker.cli_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: none
diff_mode:
support: none
idempotent:
support: N/A
details:
- Whether the executed command is idempotent depends on the command.
options:
service:
description:
- The service to run the command in.
type: str
required: true
index:
description:
- The index of the container to run the command in if the service has multiple replicas.
type: int
argv:
type: list
elements: str
description:
- The command to execute.
- Since this is a list of arguments, no quoting is needed.
- Exactly one of O(argv) or O(command) must be specified.
command:
type: str
description:
- The command to execute.
- Exactly one of O(argv) or O(command) must be specified.
chdir:
type: str
description:
- The directory to run the command in.
detach:
description:
- Whether to run the command synchronously (O(detach=false), default) or asynchronously (O(detach=true)).
- If set to V(true), O(stdin) cannot be provided, and the return values RV(stdout), RV(stderr), and RV(rc) are not returned.
type: bool
default: false
user:
type: str
description:
- If specified, the user to execute this command with.
stdin:
type: str
description:
- Set the stdin of the command directly to the specified value.
- Can only be used if O(detach=false).
stdin_add_newline:
type: bool
default: true
description:
- If set to V(true), appends a newline to O(stdin).
strip_empty_ends:
type: bool
default: true
description:
- Strip empty lines from the end of stdout/stderr in result.
privileged:
type: bool
default: false
description:
- Whether to give extended privileges to the process.
tty:
type: bool
default: true
description:
- Whether to allocate a TTY.
env:
description:
- Dictionary of environment variables with their respective values to be passed to the command ran inside the container.
- Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (for example V("true"))
in order to avoid data loss.
- Please note that if you are passing values in with Jinja2 templates, like V("{{ value }}"), you need to add V(| string)
to prevent Ansible to convert strings such as V("true") back to booleans. The correct way is to use V("{{ value |
string }}").
type: dict
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_compose_v2
notes:
- If you need to evaluate environment variables of the container in O(command) or O(argv), you need to pass the command
through a shell, like O(command=/bin/sh -c "echo $ENV_VARIABLE"). The same needs to be done in case you want to use glob patterns
or other shell features such as redirects.
"""
EXAMPLES = r"""
---
- name: Run a simple command (command)
community.docker.docker_compose_v2_exec:
service: foo
command: /bin/bash -c "ls -lah"
chdir: /root
register: result
- name: Print stdout
ansible.builtin.debug:
var: result.stdout
- name: Run a simple command (argv)
community.docker.docker_compose_v2_exec:
service: foo
argv:
- /bin/bash
- "-c"
- "ls -lah > /dev/stderr"
chdir: /root
register: result
- name: Print stderr lines
ansible.builtin.debug:
var: result.stderr_lines
"""
RETURN = r"""
stdout:
type: str
returned: success and O(detach=false)
description:
- The standard output of the container command.
stderr:
type: str
returned: success and O(detach=false)
description:
- The standard error output of the container command.
rc:
type: int
returned: success and O(detach=false)
sample: 0
description:
- The exit code of the command.
"""
import shlex
import traceback
import typing as t
from ansible.module_utils.common.text.converters import to_text
from ansible_collections.community.docker.plugins.module_utils._common_cli import (
AnsibleModuleDockerClient,
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._compose_v2 import (
BaseComposeManager,
common_compose_argspec_ex,
)
class ExecManager(BaseComposeManager):
def __init__(self, client: AnsibleModuleDockerClient) -> None:
super().__init__(client)
parameters = self.client.module.params
self.service: str = parameters["service"]
self.index: int | None = parameters["index"]
self.chdir: str | None = parameters["chdir"]
self.detach: bool = parameters["detach"]
self.user: str | None = parameters["user"]
self.stdin: str | None = parameters["stdin"]
self.strip_empty_ends: bool = parameters["strip_empty_ends"]
self.privileged: bool = parameters["privileged"]
self.tty: bool = parameters["tty"]
self.env: dict[str, t.Any] = parameters["env"]
self.argv: list[str]
if parameters["command"] is not None:
self.argv = shlex.split(parameters["command"])
else:
self.argv = parameters["argv"]
if self.detach and self.stdin is not None:
self.fail("If detach=true, stdin cannot be provided.")
stdin_add_newline: bool = parameters["stdin_add_newline"]
if self.stdin is not None and stdin_add_newline:
self.stdin += "\n"
if self.env is not None:
for name, value in self.env.items():
if not isinstance(value, str):
self.fail(
"Non-string value found for env option. Ambiguous env options must be "
"wrapped in quotes to avoid them being interpreted when directly specified "
"in YAML, or explicitly converted to strings when the option is templated. "
f"Key: {name}"
)
def get_exec_cmd(self, dry_run: bool) -> list[str]:
args = self.get_base_args(plain_progress=True) + ["exec"]
if self.index is not None:
args.extend(["--index", str(self.index)])
if self.chdir is not None:
args.extend(["--workdir", self.chdir])
if self.detach:
args.extend(["--detach"])
if self.user is not None:
args.extend(["--user", self.user])
if self.privileged:
args.append("--privileged")
if not self.tty:
args.append("--no-TTY")
if self.env:
for name, value in list(self.env.items()):
args.append("--env")
args.append(f"{name}={value}")
args.append("--")
args.append(self.service)
args.extend(self.argv)
return args
def run(self) -> dict[str, t.Any]:
args = self.get_exec_cmd(self.check_mode)
kwargs: dict[str, t.Any] = {
"cwd": self.project_src,
}
if self.stdin is not None:
kwargs["data"] = self.stdin.encode("utf-8")
if self.detach:
kwargs["check_rc"] = True
rc, stdout_b, stderr_b = self.client.call_cli(*args, **kwargs)
if self.detach:
return {}
stdout = to_text(stdout_b)
stderr = to_text(stderr_b)
if self.strip_empty_ends:
stdout = stdout.rstrip("\r\n")
stderr = stderr.rstrip("\r\n")
return {
"changed": True,
"rc": rc,
"stdout": stdout,
"stderr": stderr,
}
def main() -> None:
argument_spec = {
"service": {"type": "str", "required": True},
"index": {"type": "int"},
"argv": {"type": "list", "elements": "str"},
"command": {"type": "str"},
"chdir": {"type": "str"},
"detach": {"type": "bool", "default": False},
"user": {"type": "str"},
"stdin": {"type": "str"},
"stdin_add_newline": {"type": "bool", "default": True},
"strip_empty_ends": {"type": "bool", "default": True},
"privileged": {"type": "bool", "default": False},
"tty": {"type": "bool", "default": True},
"env": {"type": "dict"},
}
argspec_ex = common_compose_argspec_ex()
argument_spec.update(argspec_ex.pop("argspec"))
client = AnsibleModuleDockerClient(
argument_spec=argument_spec,
supports_check_mode=False,
needs_api_version=False,
**argspec_ex,
)
try:
manager = ExecManager(client)
result = manager.run()
manager.cleanup()
client.module.exit_json(**result)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,216 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_compose_v2_pull
short_description: Pull a Docker compose project
version_added: 3.6.0
description:
- Uses Docker Compose to pull images for a project.
extends_documentation_fragment:
- community.docker._compose_v2
- community.docker._compose_v2.minimum_version
- community.docker._docker.cli_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: full
details:
- If O(policy=always), the module will always indicate a change. Docker Compose does not give any information whether
pulling would update the image or not.
diff_mode:
support: none
idempotent:
support: full
options:
policy:
description:
- Whether to pull images before running. This is used when C(docker compose up) is ran.
- V(always) ensures that the images are always pulled, even when already present on the Docker daemon.
- V(missing) only pulls them when they are not present on the Docker daemon. This is only supported since Docker Compose
2.22.0.
type: str
choices:
- always
- missing
default: always
ignore_buildable:
description:
- If set to V(true), will not pull images that can be built.
type: bool
default: false
version_added: 3.12.0
include_deps:
description:
- If set to V(true), also pull services that are declared as dependencies.
- This only makes sense if O(services) is used.
type: bool
default: false
version_added: 3.12.0
services:
description:
- Specifies a subset of services to be targeted.
type: list
elements: str
version_added: 3.12.0
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_compose_v2
"""
EXAMPLES = r"""
---
- name: Pull images for flask project
community.docker.docker_compose_v2_pull:
project_src: /path/to/flask
"""
RETURN = r"""
actions:
description:
- A list of actions that have been applied.
returned: success
type: list
elements: dict
contains:
what:
description:
- What kind of resource was changed.
type: str
sample: container
choices:
- image
- unknown
id:
description:
- The ID of the resource that was changed.
type: str
sample: container
status:
description:
- The status change that happened.
type: str
sample: Pulling
choices:
- Pulling
"""
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._common_cli import (
AnsibleModuleDockerClient,
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._compose_v2 import (
BaseComposeManager,
common_compose_argspec_ex,
)
from ansible_collections.community.docker.plugins.module_utils._version import (
LooseVersion,
)
class PullManager(BaseComposeManager):
def __init__(self, client: AnsibleModuleDockerClient) -> None:
super().__init__(client)
parameters = self.client.module.params
self.policy: t.Literal["always", "missing"] = parameters["policy"]
self.ignore_buildable: bool = parameters["ignore_buildable"]
self.include_deps: bool = parameters["include_deps"]
self.services: list[str] = parameters["services"] or []
if self.policy != "always" and self.compose_version < LooseVersion("2.22.0"):
# https://github.com/docker/compose/pull/10981 - 2.22.0
self.fail(
f"A pull policy other than always is only supported since Docker Compose 2.22.0. {self.client.get_cli()} has version {self.compose_version}"
)
if self.ignore_buildable and self.compose_version < LooseVersion("2.15.0"):
# https://github.com/docker/compose/pull/10134 - 2.15.0
self.fail(
f"--ignore-buildable is only supported since Docker Compose 2.15.0. {self.client.get_cli()} has version {self.compose_version}"
)
def get_pull_cmd(self, dry_run: bool) -> list[str]:
args = self.get_base_args() + ["pull"]
if self.policy != "always":
args.extend(["--policy", self.policy])
if self.ignore_buildable:
args.append("--ignore-buildable")
if self.include_deps:
args.append("--include-deps")
if dry_run:
args.append("--dry-run")
args.append("--")
for service in self.services:
args.append(service)
return args
def run(self) -> dict[str, t.Any]:
result: dict[str, t.Any] = {}
args = self.get_pull_cmd(self.check_mode)
rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
self.emit_warnings(events)
self.update_result(
result,
events,
stdout,
stderr,
ignore_service_pull_events=self.policy != "missing" and not self.check_mode,
)
self.update_failed(result, events, args, stdout, stderr, rc)
self.cleanup_result(result)
return result
def main() -> None:
argument_spec = {
"policy": {
"type": "str",
"choices": ["always", "missing"],
"default": "always",
},
"ignore_buildable": {"type": "bool", "default": False},
"include_deps": {"type": "bool", "default": False},
"services": {"type": "list", "elements": "str"},
}
argspec_ex = common_compose_argspec_ex()
argument_spec.update(argspec_ex.pop("argspec"))
client = AnsibleModuleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
needs_api_version=False,
**argspec_ex,
)
try:
manager = PullManager(client)
result = manager.run()
manager.cleanup()
client.module.exit_json(**result)
except DockerException as e:
client.fail(
f"An unexpected docker error occurred: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,441 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_compose_v2_run
short_description: Run command in a new container of a Compose service
version_added: 3.13.0
description:
- Uses Docker Compose to run a command in a new container for a service.
- This encapsulates C(docker compose run).
extends_documentation_fragment:
- community.docker._compose_v2
- community.docker._compose_v2.minimum_version
- community.docker._docker.cli_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: none
diff_mode:
support: none
idempotent:
support: N/A
details:
- Whether the executed command is idempotent depends on the command.
options:
service:
description:
- The service to run the command in.
type: str
required: true
argv:
type: list
elements: str
description:
- The command to execute.
- Since this is a list of arguments, no quoting is needed.
- O(argv) or O(command) are mutually exclusive.
command:
type: str
description:
- The command to execute.
- O(argv) or O(command) are mutually exclusive.
build:
description:
- Build image before starting container.
- Note that building can insert information into RV(stdout) or RV(stderr).
type: bool
default: false
cap_add:
description:
- Linux capabilities to add to the container.
type: list
elements: str
cap_drop:
description:
- Linux capabilities to drop from the container.
type: list
elements: str
entrypoint:
description:
- Override the entrypoint of the container image.
type: str
interactive:
description:
- Whether to keep STDIN open even if not attached.
type: bool
default: true
labels:
description:
- Add or override labels to the container.
type: list
elements: str
name:
description:
- Assign a name to the container.
type: str
no_deps:
description:
- Do not start linked services.
type: bool
default: false
publish:
description:
- Publish a container's port(s) to the host.
type: list
elements: str
quiet_pull:
description:
- Pull without printing progress information.
- Note that pulling can insert information into RV(stdout) or RV(stderr).
type: bool
default: false
remove_orphans:
description:
- Remove containers for services not defined in the Compose file.
type: bool
default: false
cleanup:
description:
- Automatically remove th econtainer when it exits.
- Corresponds to the C(--rm) option of C(docker compose run).
type: bool
default: false
service_ports:
description:
- Run command with all service's ports enabled and mapped to the host.
type: bool
default: false
use_aliases:
description:
- Use the service's network C(useAliases) in the network(s) the container connects to.
type: bool
default: false
volumes:
description:
- Bind mount one or more volumes.
type: list
elements: str
chdir:
type: str
description:
- The directory to run the command in.
detach:
description:
- Whether to run the command synchronously (O(detach=false), default) or asynchronously (O(detach=true)).
- If set to V(true), O(stdin) cannot be provided, and the return values RV(stdout), RV(stderr), and RV(rc) are not returned.
Instead, the return value RV(container_id) is provided.
type: bool
default: false
user:
type: str
description:
- If specified, the user to execute this command with.
stdin:
type: str
description:
- Set the stdin of the command directly to the specified value.
- Can only be used if O(detach=false).
stdin_add_newline:
type: bool
default: true
description:
- If set to V(true), appends a newline to O(stdin).
strip_empty_ends:
type: bool
default: true
description:
- Strip empty lines from the end of stdout/stderr in result.
tty:
type: bool
default: true
description:
- Whether to allocate a TTY.
env:
description:
- Dictionary of environment variables with their respective values to be passed to the command ran inside the container.
- Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (for example V("true"))
in order to avoid data loss.
- Please note that if you are passing values in with Jinja2 templates, like V("{{ value }}"), you need to add V(| string)
to prevent Ansible to convert strings such as V("true") back to booleans. The correct way is to use V("{{ value |
string }}").
type: dict
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_compose_v2
notes:
- If you need to evaluate environment variables of the container in O(command) or O(argv), you need to pass the command
through a shell, like O(command=/bin/sh -c "echo $ENV_VARIABLE"). The same needs to be done in case you want to use glob patterns
or other shell features such as redirects.
"""
EXAMPLES = r"""
---
- name: Run a simple command (command)
community.docker.docker_compose_v2_run:
service: foo
command: /bin/bash -c "ls -lah"
chdir: /root
register: result
- name: Print stdout
ansible.builtin.debug:
var: result.stdout
- name: Run a simple command (argv)
community.docker.docker_compose_v2_run:
service: foo
argv:
- /bin/bash
- "-c"
- "ls -lah > /dev/stderr"
chdir: /root
register: result
- name: Print stderr lines
ansible.builtin.debug:
var: result.stderr_lines
"""
RETURN = r"""
container_id:
type: str
returned: success and O(detach=true)
description:
- The ID of the created container.
stdout:
type: str
returned: success and O(detach=false)
description:
- The standard output of the container command.
stderr:
type: str
returned: success and O(detach=false)
description:
- The standard error output of the container command.
rc:
type: int
returned: success and O(detach=false)
sample: 0
description:
- The exit code of the command.
"""
import shlex
import traceback
import typing as t
from ansible.module_utils.common.text.converters import to_text
from ansible_collections.community.docker.plugins.module_utils._common_cli import (
AnsibleModuleDockerClient,
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._compose_v2 import (
BaseComposeManager,
common_compose_argspec_ex,
)
class ExecManager(BaseComposeManager):
def __init__(self, client: AnsibleModuleDockerClient) -> None:
super().__init__(client)
parameters = self.client.module.params
self.service: str = parameters["service"]
self.build: bool = parameters["build"]
self.cap_add: list[str] | None = parameters["cap_add"]
self.cap_drop: list[str] | None = parameters["cap_drop"]
self.entrypoint: str | None = parameters["entrypoint"]
self.interactive: bool = parameters["interactive"]
self.labels: list[str] | None = parameters["labels"]
self.name: str | None = parameters["name"]
self.no_deps: bool = parameters["no_deps"]
self.publish: list[str] | None = parameters["publish"]
self.quiet_pull: bool = parameters["quiet_pull"]
self.remove_orphans: bool = parameters["remove_orphans"]
self.do_cleanup: bool = parameters["cleanup"]
self.service_ports: bool = parameters["service_ports"]
self.use_aliases: bool = parameters["use_aliases"]
self.volumes: list[str] | None = parameters["volumes"]
self.chdir: str | None = parameters["chdir"]
self.detach: bool = parameters["detach"]
self.user: str | None = parameters["user"]
self.stdin: str | None = parameters["stdin"]
self.strip_empty_ends: bool = parameters["strip_empty_ends"]
self.tty: bool = parameters["tty"]
self.env: dict[str, t.Any] | None = parameters["env"]
self.argv: list[str]
if parameters["command"] is not None:
self.argv = shlex.split(parameters["command"])
else:
self.argv = parameters["argv"]
if self.detach and self.stdin is not None:
self.fail("If detach=true, stdin cannot be provided.")
stdin_add_newline: bool = parameters["stdin_add_newline"]
if self.stdin is not None and stdin_add_newline:
self.stdin += "\n"
if self.env is not None:
for name, value in self.env.items():
if not isinstance(value, str):
self.fail(
"Non-string value found for env option. Ambiguous env options must be "
"wrapped in quotes to avoid them being interpreted when directly specified "
"in YAML, or explicitly converted to strings when the option is templated. "
f"Key: {name}"
)
def get_run_cmd(self, dry_run: bool) -> list[str]:
args = self.get_base_args(plain_progress=True) + ["run"]
if self.build:
args.append("--build")
if self.cap_add:
for cap in self.cap_add:
args.extend(["--cap-add", cap])
if self.cap_drop:
for cap in self.cap_drop:
args.extend(["--cap-drop", cap])
if self.entrypoint is not None:
args.extend(["--entrypoint", self.entrypoint])
if not self.interactive:
args.append("--no-interactive")
if self.labels:
for label in self.labels:
args.extend(["--label", label])
if self.name is not None:
args.extend(["--name", self.name])
if self.no_deps:
args.append("--no-deps")
if self.publish:
for publish in self.publish:
args.extend(["--publish", publish])
if self.quiet_pull:
args.append("--quiet-pull")
if self.remove_orphans:
args.append("--remove-orphans")
if self.do_cleanup:
args.append("--rm")
if self.service_ports:
args.append("--service-ports")
if self.use_aliases:
args.append("--use-aliases")
if self.volumes:
for volume in self.volumes:
args.extend(["--volume", volume])
if self.chdir is not None:
args.extend(["--workdir", self.chdir])
if self.detach:
args.extend(["--detach"])
if self.user is not None:
args.extend(["--user", self.user])
if not self.tty:
args.append("--no-TTY")
if self.env:
for name, value in list(self.env.items()):
args.append("--env")
args.append(f"{name}={value}")
args.append("--")
args.append(self.service)
if self.argv:
args.extend(self.argv)
return args
def run(self) -> dict[str, t.Any]:
args = self.get_run_cmd(self.check_mode)
kwargs: dict[str, t.Any] = {
"cwd": self.project_src,
}
if self.stdin is not None:
kwargs["data"] = self.stdin.encode("utf-8")
if self.detach:
kwargs["check_rc"] = True
rc, stdout_b, stderr_b = self.client.call_cli(*args, **kwargs)
if self.detach:
return {
"container_id": to_text(stdout_b.strip()),
}
stdout = to_text(stdout_b)
stderr = to_text(stderr_b)
if self.strip_empty_ends:
stdout = stdout.rstrip("\r\n")
stderr = stderr.rstrip("\r\n")
return {
"changed": True,
"rc": rc,
"stdout": stdout,
"stderr": stderr,
}
def main() -> None:
argument_spec = {
"service": {"type": "str", "required": True},
"argv": {"type": "list", "elements": "str"},
"command": {"type": "str"},
"build": {"type": "bool", "default": False},
"cap_add": {"type": "list", "elements": "str"},
"cap_drop": {"type": "list", "elements": "str"},
"entrypoint": {"type": "str"},
"interactive": {"type": "bool", "default": True},
"labels": {"type": "list", "elements": "str"},
"name": {"type": "str"},
"no_deps": {"type": "bool", "default": False},
"publish": {"type": "list", "elements": "str"},
"quiet_pull": {"type": "bool", "default": False},
"remove_orphans": {"type": "bool", "default": False},
"cleanup": {"type": "bool", "default": False},
"service_ports": {"type": "bool", "default": False},
"use_aliases": {"type": "bool", "default": False},
"volumes": {"type": "list", "elements": "str"},
"chdir": {"type": "str"},
"detach": {"type": "bool", "default": False},
"user": {"type": "str"},
"stdin": {"type": "str"},
"stdin_add_newline": {"type": "bool", "default": True},
"strip_empty_ends": {"type": "bool", "default": True},
"tty": {"type": "bool", "default": True},
"env": {"type": "dict"},
}
argspec_ex = common_compose_argspec_ex()
argument_spec.update(argspec_ex.pop("argspec"))
client = AnsibleModuleDockerClient(
argument_spec=argument_spec,
supports_check_mode=False,
needs_api_version=False,
**argspec_ex,
)
try:
manager = ExecManager(client)
result = manager.run()
manager.cleanup()
client.module.exit_json(**result)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,447 @@
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_config
short_description: Manage docker configs
description:
- Create and remove Docker configs in a Swarm environment. Similar to C(docker config create) and C(docker config rm).
- Adds to the metadata of new configs C(ansible_key), an encrypted hash representation of the data, which is then used in
future runs to test if a config has changed. If C(ansible_key) is not present, then a config will not be updated unless
the O(force) option is set.
- Updates to configs are performed by removing the config and creating it again.
extends_documentation_fragment:
- community.docker._docker
- community.docker._docker.docker_py_2_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: full
diff_mode:
support: none
idempotent:
support: partial
details:
- If O(force=true) the module is not idempotent.
options:
data:
description:
- The value of the config.
- Mutually exclusive with O(data_src). One of O(data) and O(data_src) is required if O(state=present).
type: str
data_is_b64:
description:
- If set to V(true), the data is assumed to be Base64 encoded and will be decoded before being used.
- To use binary O(data), it is better to keep it Base64 encoded and let it be decoded by this option.
type: bool
default: false
data_src:
description:
- The file on the target from which to read the config.
- Mutually exclusive with O(data). One of O(data) and O(data_src) is required if O(state=present).
type: path
version_added: 1.10.0
labels:
description:
- A map of key:value meta data, where both the C(key) and C(value) are expected to be a string.
- If new meta data is provided, or existing meta data is modified, the config will be updated by removing it and creating
it again.
type: dict
force:
description:
- Use with O(state=present) to always remove and recreate an existing config.
- If V(true), an existing config will be replaced, even if it has not been changed.
type: bool
default: false
rolling_versions:
description:
- If set to V(true), configs are created with an increasing version number appended to their name.
- Adds a label containing the version number to the managed configs with the name C(ansible_version).
type: bool
default: false
version_added: 2.2.0
versions_to_keep:
description:
- When using O(rolling_versions), the number of old versions of the config to keep.
- Extraneous old configs are deleted after the new one is created.
- Set to V(-1) to keep everything or V(0) or V(1) to keep only the current one.
type: int
default: 5
version_added: 2.2.0
name:
description:
- The name of the config.
type: str
required: true
state:
description:
- Set to V(present), if the config should exist, and V(absent), if it should not.
type: str
default: present
choices:
- absent
- present
template_driver:
description:
- Set to V(golang) to use a Go template in O(data) or a Go template file in O(data_src).
type: str
choices:
- golang
version_added: 2.5.0
requirements:
- "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 2.6.0"
- "Docker API >= 1.30"
author:
- Chris Houseknecht (@chouseknecht)
- John Hu (@ushuz)
"""
EXAMPLES = r"""
---
- name: Create config foo (from a file on the control machine)
community.docker.docker_config:
name: foo
# If the file is JSON or binary, Ansible might modify it (because
# it is first decoded and later re-encoded). Base64-encoding the
# file directly after reading it prevents this to happen.
data: "{{ lookup('file', '/path/to/config/file') | b64encode }}"
data_is_b64: true
state: present
- name: Create config foo (from a file on the target machine)
community.docker.docker_config:
name: foo
data_src: /path/to/config/file
state: present
- name: Change the config data
community.docker.docker_config:
name: foo
data: Goodnight everyone!
labels:
bar: baz
one: '1'
state: present
- name: Add a new label
community.docker.docker_config:
name: foo
data: Goodnight everyone!
labels:
bar: baz
one: '1'
# Adding a new label will cause a remove/create of the config
two: '2'
state: present
- name: No change
community.docker.docker_config:
name: foo
data: Goodnight everyone!
labels:
bar: baz
one: '1'
# Even though 'two' is missing, there is no change to the existing config
state: present
- name: Update an existing label
community.docker.docker_config:
name: foo
data: Goodnight everyone!
labels:
bar: monkey # Changing a label will cause a remove/create of the config
one: '1'
state: present
- name: Force the (re-)creation of the config
community.docker.docker_config:
name: foo
data: Goodnight everyone!
force: true
state: present
- name: Remove config foo
community.docker.docker_config:
name: foo
state: absent
"""
RETURN = r"""
config_id:
description:
- The ID assigned by Docker to the config object.
returned: success and O(state=present)
type: str
sample: 'hzehrmyjigmcp2gb6nlhmjqcv'
config_name:
description:
- The name of the created config object.
returned: success and O(state=present)
type: str
sample: 'awesome_config'
version_added: 2.2.0
"""
import base64
import hashlib
import traceback
import typing as t
try:
from docker.errors import APIError, DockerException
except ImportError:
# missing Docker SDK for Python handled in ansible.module_utils.docker.common
pass
from ansible.module_utils.common.text.converters import to_bytes
from ansible_collections.community.docker.plugins.module_utils._common import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
compare_generic,
sanitize_labels,
)
class ConfigManager(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None:
super().__init__()
self.client = client
self.results = results
self.check_mode = self.client.check_mode
parameters = self.client.module.params
self.name = parameters.get("name")
self.state = parameters.get("state")
self.data = parameters.get("data")
if self.data is not None:
if parameters.get("data_is_b64"):
self.data = base64.b64decode(self.data)
else:
self.data = to_bytes(self.data)
data_src = parameters.get("data_src")
if data_src is not None:
try:
with open(data_src, "rb") as f:
self.data = f.read()
except Exception as exc: # pylint: disable=broad-exception-caught
self.client.fail(f"Error while reading {data_src}: {exc}")
self.labels = parameters.get("labels")
self.force = parameters.get("force")
self.rolling_versions = parameters.get("rolling_versions")
self.versions_to_keep = parameters.get("versions_to_keep")
self.template_driver = parameters.get("template_driver")
if self.rolling_versions:
self.version = 0
self.data_key: str | None = None
self.configs: list[dict[str, t.Any]] = []
def __call__(self) -> None:
self.get_config()
if self.state == "present":
self.data_key = hashlib.sha224(self.data).hexdigest()
self.present()
self.remove_old_versions()
elif self.state == "absent":
self.absent()
def get_version(self, config: dict[str, t.Any]) -> int:
try:
return int(
config.get("Spec", {}).get("Labels", {}).get("ansible_version", 0)
)
except ValueError:
return 0
def remove_old_versions(self) -> None:
if not self.rolling_versions or self.versions_to_keep < 0:
return
if not self.check_mode:
while len(self.configs) > max(self.versions_to_keep, 1):
self.remove_config(self.configs.pop(0))
def get_config(self) -> None:
"""Find an existing config."""
try:
configs = self.client.configs(filters={"name": self.name})
except APIError as exc:
self.client.fail(f"Error accessing config {self.name}: {exc}")
if self.rolling_versions:
self.configs = [
config
for config in configs
if config["Spec"]["Name"].startswith(f"{self.name}_v")
]
self.configs.sort(key=self.get_version)
else:
self.configs = [
config for config in configs if config["Spec"]["Name"] == self.name
]
def create_config(self) -> str | None:
"""Create a new config"""
config_id: str | dict[str, t.Any] | None = None
# We ca not see the data after creation, so adding a label we can use for idempotency check
labels = {"ansible_key": self.data_key}
if self.rolling_versions:
self.version += 1
labels["ansible_version"] = str(self.version)
self.name = f"{self.name}_v{self.version}"
if self.labels:
labels.update(self.labels)
try:
if not self.check_mode:
# only use templating argument when self.template_driver is defined
kwargs = {}
if self.template_driver:
kwargs["templating"] = {"name": self.template_driver}
config_id = self.client.create_config(
self.name, self.data, labels=labels, **kwargs
)
self.configs += self.client.configs(filters={"id": config_id})
except APIError as exc:
self.client.fail(f"Error creating config: {exc}")
if isinstance(config_id, dict):
return config_id["ID"]
return config_id
def remove_config(self, config: dict[str, t.Any]) -> None:
try:
if not self.check_mode:
self.client.remove_config(config["ID"])
except APIError as exc:
self.client.fail(f"Error removing config {config['Spec']['Name']}: {exc}")
def present(self) -> None:
"""Handles state == 'present', creating or updating the config"""
if self.configs:
config = self.configs[-1]
self.results["config_id"] = config["ID"]
self.results["config_name"] = config["Spec"]["Name"]
data_changed = False
template_driver_changed = False
attrs = config.get("Spec", {})
if attrs.get("Labels", {}).get("ansible_key"):
if attrs["Labels"]["ansible_key"] != self.data_key:
data_changed = True
else:
if not self.force:
self.client.module.warn(
"'ansible_key' label not found. Config will not be changed unless the force parameter is set to 'true'"
)
# template_driver has changed if it was set in the previous config
# and now it differs, or if it was not set but now it is.
if attrs.get("Templating", {}).get("Name"):
if attrs["Templating"]["Name"] != self.template_driver:
template_driver_changed = True
elif self.template_driver:
template_driver_changed = True
labels_changed = not compare_generic(
self.labels, attrs.get("Labels"), "allow_more_present", "dict"
)
if self.rolling_versions:
self.version = self.get_version(config)
if data_changed or template_driver_changed or labels_changed or self.force:
# if something changed or force, delete and re-create the config
if not self.rolling_versions:
self.absent()
config_id = self.create_config()
self.results["changed"] = True
self.results["config_id"] = config_id
self.results["config_name"] = self.name
else:
self.results["changed"] = True
self.results["config_id"] = self.create_config()
self.results["config_name"] = self.name
def absent(self) -> None:
"""Handles state == 'absent', removing the config"""
if self.configs:
for config in self.configs:
self.remove_config(config)
self.results["changed"] = True
def main() -> None:
argument_spec = {
"name": {"type": "str", "required": True},
"state": {
"type": "str",
"default": "present",
"choices": ["absent", "present"],
},
"data": {"type": "str"},
"data_is_b64": {"type": "bool", "default": False},
"data_src": {"type": "path"},
"labels": {"type": "dict"},
"force": {"type": "bool", "default": False},
"rolling_versions": {"type": "bool", "default": False},
"versions_to_keep": {"type": "int", "default": 5},
"template_driver": {"type": "str", "choices": ["golang"]},
}
required_if = [
("state", "present", ["data", "data_src"], True),
]
mutually_exclusive = [
("data", "data_src"),
]
option_minimal_versions = {
"template_driver": {"docker_py_version": "5.0.3", "docker_api_version": "1.37"},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=required_if,
mutually_exclusive=mutually_exclusive,
min_docker_version="2.6.0",
min_docker_api_version="1.30",
option_minimal_versions=option_minimal_versions,
)
sanitize_labels(client.module.params["labels"], "labels", client)
try:
results = {
"changed": False,
}
ConfigManager(client, results)()
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,345 @@
#!/usr/bin/python
#
# Copyright (c) 2021, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_container_exec
short_description: Execute command in a docker container
version_added: 1.5.0
description:
- Executes a command in a Docker container.
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: none
diff_mode:
support: none
idempotent:
support: N/A
details:
- Whether the executed command is idempotent depends on the command.
options:
container:
type: str
required: true
description:
- The name of the container to execute the command in.
argv:
type: list
elements: str
description:
- The command to execute.
- Since this is a list of arguments, no quoting is needed.
- Exactly one of O(argv) or O(command) must be specified.
command:
type: str
description:
- The command to execute.
- Exactly one of O(argv) or O(command) must be specified.
chdir:
type: str
description:
- The directory to run the command in.
detach:
description:
- Whether to run the command synchronously (O(detach=false), default) or asynchronously (O(detach=true)).
- If set to V(true), O(stdin) cannot be provided, and the return values RV(stdout), RV(stderr), and RV(rc) are not returned.
type: bool
default: false
version_added: 2.1.0
user:
type: str
description:
- If specified, the user to execute this command with.
stdin:
type: str
description:
- Set the stdin of the command directly to the specified value.
- Can only be used if O(detach=false).
stdin_add_newline:
type: bool
default: true
description:
- If set to V(true), appends a newline to O(stdin).
strip_empty_ends:
type: bool
default: true
description:
- Strip empty lines from the end of stdout/stderr in result.
tty:
type: bool
default: false
description:
- Whether to allocate a TTY.
env:
description:
- Dictionary of environment variables with their respective values to be passed to the command ran inside the container.
- Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (for example V("true"))
in order to avoid data loss.
- Please note that if you are passing values in with Jinja2 templates, like V("{{ value }}"), you need to add V(| string)
to prevent Ansible to convert strings such as V("true") back to booleans. The correct way is to use V("{{ value |
string }}").
type: dict
version_added: 2.1.0
notes:
- Does B(not work with TCP TLS sockets) when using O(stdin). This is caused by the inability to send C(close_notify) without
closing the connection with Python's C(SSLSocket)s. See U(https://github.com/ansible-collections/community.docker/issues/605)
for more information.
- If you need to evaluate environment variables of the container in O(command) or O(argv), you need to pass the command
through a shell, like O(command=/bin/sh -c "echo $ENV_VARIABLE"). The same needs to be done in case you want to use glob patterns
or other shell features such as redirects.
author:
- "Felix Fontein (@felixfontein)"
requirements:
- "Docker API >= 1.25"
"""
EXAMPLES = r"""
---
- name: Run a simple command (command)
community.docker.docker_container_exec:
container: foo
command: /bin/bash -c "ls -lah"
chdir: /root
register: result
- name: Print stdout
ansible.builtin.debug:
var: result.stdout
- name: Run a simple command (argv)
community.docker.docker_container_exec:
container: foo
argv:
- /bin/bash
- "-c"
- "ls -lah > /dev/stderr"
chdir: /root
register: result
- name: Print stderr lines
ansible.builtin.debug:
var: result.stderr_lines
"""
RETURN = r"""
stdout:
type: str
returned: success and O(detach=false)
description:
- The standard output of the container command.
stderr:
type: str
returned: success and O(detach=false)
description:
- The standard error output of the container command.
rc:
type: int
returned: success and O(detach=false)
sample: 0
description:
- The exit code of the command.
exec_id:
type: str
returned: success and O(detach=true)
sample: 249d9e3075655baf705ed8f40488c5e9434049cf3431976f1bfdb73741c574c5
description:
- The execution ID of the command.
version_added: 2.1.0
"""
import shlex
import traceback
import typing as t
from ansible.module_utils.common.text.converters import to_bytes, to_text
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
APIError,
DockerException,
NotFound,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
format_environment,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._socket_handler import (
DockerSocketHandlerModule,
)
def main() -> None:
argument_spec = {
"container": {"type": "str", "required": True},
"argv": {"type": "list", "elements": "str"},
"command": {"type": "str"},
"chdir": {"type": "str"},
"detach": {"type": "bool", "default": False},
"user": {"type": "str"},
"stdin": {"type": "str"},
"stdin_add_newline": {"type": "bool", "default": True},
"strip_empty_ends": {"type": "bool", "default": True},
"tty": {"type": "bool", "default": False},
"env": {"type": "dict"},
}
option_minimal_versions = {
"chdir": {"docker_api_version": "1.35"},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
option_minimal_versions=option_minimal_versions,
mutually_exclusive=[("argv", "command")],
required_one_of=[("argv", "command")],
)
container: str = client.module.params["container"]
argv: list[str] | None = client.module.params["argv"]
command: str | None = client.module.params["command"]
chdir: str | None = client.module.params["chdir"]
detach: bool = client.module.params["detach"]
user: str | None = client.module.params["user"]
stdin: str | None = client.module.params["stdin"]
strip_empty_ends: bool = client.module.params["strip_empty_ends"]
tty: bool = client.module.params["tty"]
env: dict[str, t.Any] | None = client.module.params["env"]
if env is not None:
for name, value in env.items():
if not isinstance(value, str):
client.module.fail_json(
msg="Non-string value found for env option. Ambiguous env options must be "
"wrapped in quotes to avoid them being interpreted when directly specified "
"in YAML, or explicitly converted to strings when the option is templated. "
f"Key: {name}"
)
if command is not None:
argv = shlex.split(command)
assert argv is not None
if detach and stdin is not None:
client.module.fail_json(msg="If detach=true, stdin cannot be provided.")
if stdin is not None and client.module.params["stdin_add_newline"]:
stdin += "\n"
try:
data = {
"Container": container,
"User": user or "",
"Privileged": False,
"Tty": False,
"AttachStdin": bool(stdin),
"AttachStdout": True,
"AttachStderr": True,
"Cmd": argv,
"Env": format_environment(env) if env is not None else None,
}
if chdir is not None:
data["WorkingDir"] = chdir
exec_data = client.post_json_to_json(
"/containers/{0}/exec", container, data=data
)
exec_id: str = exec_data["Id"]
data = {
"Tty": tty,
"Detach": detach,
}
if detach:
client.post_json_to_text("/exec/{0}/start", exec_id, data=data)
client.module.exit_json(changed=True, exec_id=exec_id)
else:
stdout: bytes | None
stderr: bytes | None
if stdin and not detach:
exec_socket = client.post_json_to_stream_socket(
"/exec/{0}/start", exec_id, data=data
)
try:
with DockerSocketHandlerModule(
exec_socket, client.module
) as exec_socket_handler:
if stdin:
exec_socket_handler.write(to_bytes(stdin))
stdout, stderr = exec_socket_handler.consume()
finally:
exec_socket.close()
elif tty:
stdout, stderr = client.post_json_to_stream(
"/exec/{0}/start",
exec_id,
data=data,
stream=False,
tty=True,
demux=True,
)
else:
stdout, stderr = client.post_json_to_stream(
"/exec/{0}/start",
exec_id,
data=data,
stream=False,
tty=False,
demux=True,
)
result = client.get_json("/exec/{0}/json", exec_id)
stdout_t = to_text(stdout or b"")
stderr_t = to_text(stderr or b"")
if strip_empty_ends:
stdout_t = stdout_t.rstrip("\r\n")
stderr_t = stderr_t.rstrip("\r\n")
client.module.exit_json(
changed=True,
stdout=stdout_t,
stderr=stderr_t,
rc=result.get("ExitCode") or 0,
)
except NotFound:
client.fail(f'Could not find container "{container}"')
except APIError as e:
if e.response is not None and e.response.status_code == 409:
client.fail(f'The container "{container}" has been paused ({e})')
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,120 @@
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_container_info
short_description: Retrieves facts about docker container
description:
- Retrieves facts about a docker container.
- Essentially returns the output of C(docker inspect <name>), similar to what M(community.docker.docker_container) returns
for a non-absent container.
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
- community.docker._attributes.info_module
- community.docker._attributes.idempotent_not_modify_state
options:
name:
description:
- The name of the container to inspect.
- When identifying an existing container name may be a name or a long or short container ID.
type: str
required: true
author:
- "Felix Fontein (@felixfontein)"
requirements:
- "Docker API >= 1.25"
"""
EXAMPLES = r"""
---
- name: Get infos on container
community.docker.docker_container_info:
name: mydata
register: result
- name: Does container exist?
ansible.builtin.debug:
msg: "The container {{ 'exists' if result.exists else 'does not exist' }}"
- name: Print information about container
ansible.builtin.debug:
var: result.container
when: result.exists
"""
RETURN = r"""
exists:
description:
- Returns whether the container exists.
type: bool
returned: always
sample: true
container:
description:
- Facts representing the current state of the container. Matches the docker inspection output.
- Will be V(none) if container does not exist.
returned: always
type: dict
sample: '{ "AppArmorProfile": "", "Args": [], "Config": { "AttachStderr": false, "AttachStdin": false, "AttachStdout": false,
"Cmd": [ "/usr/bin/supervisord" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
], "ExposedPorts": { "443/tcp": {}, "80/tcp": {} }, "Hostname": "8e47bf643eb9", "Image": "lnmp_nginx:v1", "Labels": {},
"OnBuild": null, "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": { "/tmp/lnmp/nginx-sites/logs/":
{} }, ... }'
"""
import traceback
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
def main() -> None:
argument_spec = {
"name": {"type": "str", "required": True},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
)
container_id: str = client.module.params["name"]
try:
container = client.get_container(container_id)
client.module.exit_json(
changed=False,
exists=bool(container),
container=container,
)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,325 @@
#!/usr/bin/python
#
# Copyright 2025 Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_context_info
short_description: Retrieve information on Docker contexts for the current user
version_added: 4.4.0
description:
- Return information on Docker contexts.
- This includes some generic information, as well as a RV(contexts[].config) dictionary that can be used for module defaults for all community.docker modules
that use the C(community.docker.docker) module defaults group.
extends_documentation_fragment:
- community.docker._attributes
- community.docker._attributes.info_module
- community.docker._attributes.idempotent_not_modify_state
options:
only_current:
description:
- If set to V(true), RV(contexts) will just contain the current context and none else.
- If set to V(false) (default), RV(contexts) will list all contexts, unless O(name) is specified.
- Mutually exclusive to O(name).
type: bool
default: false
name:
description:
- A specific Docker CLI context to query.
- The module will fail if this context does not exist. If you simply want to query whether a context exists,
do not specify this parameter and use Jinja2 to search the resulting list for a context of the given name instead.
- Mutually exclusive with O(only_current).
type: str
cli_context:
description:
- Override for the default context's name.
- This is preferably used for context selection when O(only_current=true),
and it is used to compute the return values RV(contexts[].current) and RV(current_context_name).
type: str
author:
- "Felix Fontein (@felixfontein)"
"""
EXAMPLES = r"""
---
- name: Get infos on contexts
community.docker.docker_context_info:
register: result
- name: Show all contexts
ansible.builtin.debug:
msg: "{{ result.contexts }}"
- name: Get current context
community.docker.docker_context_info:
only_current: true
register: docker_current_context
- name: Run community.docker modules with current context
module_defaults:
group/community.docker.docker: "{{ docker_current_context.contexts[0].config }}"
block:
- name: Task using the current context
community.docker.docker_container:
image: ubuntu:latest
name: ubuntu
state: started
"""
RETURN = r"""
contexts:
description:
- A list of all contexts (O(only_current=false), O(name) not specified),
only the current context (O(only_current=true)),
or the requested context (O(name) specified).
type: list
elements: dict
returned: success
contains:
current:
description:
- Whether this context is the current one.
type: bool
returned: success
sample: true
name:
description:
- The context's name.
type: bool
returned: success
sample: default
description:
description:
- The context's description, if available.
type: bool
returned: success
sample: My context
meta_path:
description:
- The path to the context's meta directory.
- Not present for RV(contexts[].name=default).
type: str
returned: success
sample: /home/felix/.docker/contexts/meta/0123456789abcdef01234567890abcdef0123456789abcdef0123456789abcde
tls_path:
description:
- The path to the context's TLS config directory.
- Not present for RV(contexts[].name=default).
type: str
returned: success
sample: /home/user/.docker/contexts/tls/0123456789abcdef01234567890abcdef0123456789abcdef0123456789abcde/
config:
description:
- In case the context is for Docker, contains option values to configure the community.docker modules to use this context.
- Note that the exact values returned here and their values might change over time if incompatibilities to existing modules are found.
The goal is that this configuration works fine with all modules in this collection, but we do not have the capabilities to
test all possible configuration options at the moment.
type: dict
returned: success
sample: {}
contains:
docker_host:
description:
- The Docker daemon to connect to.
type: str
returned: success and context is for Docker
sample: unix:///var/run/docker.sock
tls:
description:
- Whether the Docker context should use an unvalidated TLS connection.
type: bool
returned: success and context is for Docker
sample: false
ca_path:
description:
- The CA certificate used to validate the Docker daemon's certificate.
type: bool
returned: success, context is for Docker, TLS config is present, and CA cert is present
sample: /path/to/ca-cert.pem
client_cert:
description:
- The client certificate to authenticate with to the Docker daemon.
type: bool
returned: success, context is for Docker, TLS config is present, and client cert info is present
sample: /path/to/client-cert.pem
client_key:
description:
- The client certificate's key to authenticate with to the Docker daemon.
type: bool
returned: success, context is for Docker, TLS config is present, and client cert info is present
sample: /path/to/client-key.pem
validate_certs:
description:
- Whether the Docker context should use a validated TLS connection.
type: bool
returned: success, context is for Docker, and TLS config is present
sample: true
current_context_name:
description:
- The name of the current Docker context.
type: str
returned: success
sample: default
"""
import traceback
import typing as t
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_text
from ansible_collections.community.docker.plugins.module_utils._api.context.api import (
ContextAPI,
)
from ansible_collections.community.docker.plugins.module_utils._api.context.config import (
get_current_context_name_with_source,
)
from ansible_collections.community.docker.plugins.module_utils._api.context.context import (
IN_MEMORY,
Context,
)
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
ContextException,
DockerException,
)
if t.TYPE_CHECKING:
from ansible_collections.community.docker.plugins.module_utils._api.tls import (
TLSConfig,
)
def tls_context_to_json(context: TLSConfig | None) -> dict[str, t.Any] | None:
if context is None:
return None
return {
"client_cert": context.cert[0] if context.cert else None,
"client_key": context.cert[1] if context.cert else None,
"ca_cert": context.ca_cert,
"verify": context.verify,
# 'ssl_version': context.ssl_version, -- this isn't used anymore
}
def context_to_json(context: Context, current: bool) -> dict[str, t.Any]:
module_config: dict[str, t.Any] = {}
if "docker" in context.endpoints:
endpoint = context.endpoints["docker"]
if isinstance(endpoint.get("Host"), str):
host_str = to_text(endpoint["Host"])
# Adjust protocol name so that it works with the Docker CLI tool as well
proto = None
idx = host_str.find("://")
if idx >= 0:
proto = host_str[:idx]
host_str = host_str[idx + 3 :]
if proto in ("http", "https"):
proto = "tcp"
if proto == "http+unix":
proto = "unix"
if proto:
host_str = f"{proto}://{host_str}"
# Create config for the modules
module_config["docker_host"] = host_str
if context.tls_cfg.get("docker"):
tls_cfg = context.tls_cfg["docker"]
if tls_cfg.ca_cert:
module_config["ca_path"] = tls_cfg.ca_cert
if tls_cfg.cert:
module_config["client_cert"] = tls_cfg.cert[0]
module_config["client_key"] = tls_cfg.cert[1]
module_config["validate_certs"] = tls_cfg.verify
module_config["tls"] = True
else:
module_config["tls"] = bool(endpoint.get("SkipTLSVerify"))
return {
"current": current,
"name": context.name,
"description": context.description,
"meta_path": None if context.meta_path is IN_MEMORY else context.meta_path,
"tls_path": None if context.tls_path is IN_MEMORY else context.tls_path,
"config": module_config,
}
def main() -> None:
argument_spec = {
"only_current": {"type": "bool", "default": False},
"name": {"type": "str"},
"cli_context": {"type": "str"},
}
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
mutually_exclusive=[
("only_current", "name"),
],
)
only_current: bool = module.params["only_current"]
name: str | None = module.params["name"]
cli_context: str | None = module.params["cli_context"]
try:
if cli_context:
current_context_name, current_context_source = (
cli_context,
"cli_context module option",
)
else:
current_context_name, current_context_source = (
get_current_context_name_with_source()
)
if name:
context_or_none = ContextAPI.get_context(name)
if not context_or_none:
module.fail_json(msg=f"There is no context of name {name!r}")
contexts = [context_or_none]
elif only_current:
context_or_none = ContextAPI.get_context(current_context_name)
if not context_or_none:
module.fail_json(
msg=f"There is no context of name {current_context_name!r}, which is configured as the default context ({current_context_source})",
)
contexts = [context_or_none]
else:
contexts = ContextAPI.contexts()
json_contexts = sorted(
[
context_to_json(context, context.name == current_context_name)
for context in contexts
],
key=lambda entry: entry["name"],
)
module.exit_json(
changed=False,
contexts=json_contexts,
current_context_name=current_context_name,
)
except ContextException as e:
module.fail_json(
msg=f"Error when handling Docker contexts: {e}",
exception=traceback.format_exc(),
)
except DockerException as e:
module.fail_json(
msg=f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,404 @@
#!/usr/bin/python
#
# Copyright (c) 2019 Piotr Wojciechowski <piotr@it-playground.pl>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_host_info
short_description: Retrieves facts about docker host and lists of objects of the services
description:
- Retrieves facts about a docker host.
- Essentially returns the output of C(docker system info).
- The module also allows to list object names for containers, images, networks and volumes. It also allows to query information
on disk usage.
- The output differs depending on API version of the docker daemon.
- If the docker daemon cannot be contacted or does not meet the API version requirements, the module will fail.
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
- community.docker._attributes.idempotent_not_modify_state
attributes:
check_mode:
support: full
details:
- This action does not modify state.
diff_mode:
support: N/A
details:
- This action does not modify state.
options:
containers:
description:
- Whether to list containers.
type: bool
default: false
containers_all:
description:
- By default, only running containers are returned.
- This corresponds to the C(--all) option to C(docker container list).
type: bool
default: false
version_added: 3.4.0
containers_filters:
description:
- A dictionary of filter values used for selecting containers to list.
- 'For example, C(until: 24h).'
- 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>)
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value).
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/container_prune/#filtering) for
more information on possible filters.
type: dict
images:
description:
- Whether to list images.
type: bool
default: false
images_filters:
description:
- A dictionary of filter values used for selecting images to list.
- 'For example, C(dangling: true).'
- 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>)
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value).
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/image_prune/#filtering) for more
information on possible filters.
type: dict
networks:
description:
- Whether to list networks.
type: bool
default: false
networks_filters:
description:
- A dictionary of filter values used for selecting networks to list.
- 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>)
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value).
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/network_prune/#filtering) for
more information on possible filters.
type: dict
volumes:
description:
- Whether to list volumes.
type: bool
default: false
volumes_filters:
description:
- A dictionary of filter values used for selecting volumes to list.
- 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>)
matching when a label has a particular value, or a list of strings C(<key>)/C(<key>=<value).
- See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/volume_prune/#filtering) for more
information on possible filters.
type: dict
disk_usage:
description:
- Summary information on used disk space by all Docker layers.
- The output is a sum of images, volumes, containers and build cache.
type: bool
default: false
verbose_output:
description:
- When set to V(true) and O(networks), O(volumes), O(images), O(containers), or O(disk_usage) is set to V(true) then
output will contain verbose information about objects matching the full output of API method. For details see the
documentation of your version of Docker API at U(https://docs.docker.com/engine/api/).
- The verbose output in this module contains only subset of information returned by this module for each type of the
objects.
type: bool
default: false
author:
- Piotr Wojciechowski (@WojciechowskiPiotr)
requirements:
- "Docker API >= 1.25"
"""
EXAMPLES = r"""
---
- name: Get info on docker host
community.docker.docker_host_info:
register: result
- name: Get info on docker host and list images
community.docker.docker_host_info:
images: true
register: result
- name: Get info on docker host and list images matching the filter
community.docker.docker_host_info:
images: true
images_filters:
label: "mylabel"
register: result
- name: Get info on docker host and verbose list images
community.docker.docker_host_info:
images: true
verbose_output: true
register: result
- name: Get info on docker host and used disk space
community.docker.docker_host_info:
disk_usage: true
register: result
- name: Get info on docker host and list containers matching the filter
community.docker.docker_host_info:
containers: true
containers_filters:
label:
- key1=value1
- key2=value2
register: result
- name: Show host information
ansible.builtin.debug:
var: result.host_info
"""
RETURN = r"""
can_talk_to_docker:
description:
- Will be V(true) if the module can talk to the docker daemon.
returned: both on success and on error
type: bool
host_info:
description:
- Facts representing the basic state of the docker host. Matches the C(docker system info) output.
returned: always
type: dict
volumes:
description:
- List of dict objects containing the basic information about each volume. Keys matches the C(docker volume ls) output
unless O(verbose_output=true). See description for O(verbose_output).
returned: When O(volumes=true)
type: list
elements: dict
networks:
description:
- List of dict objects containing the basic information about each network. Keys matches the C(docker network ls) output
unless O(verbose_output=true). See description for O(verbose_output).
returned: When O(networks=true)
type: list
elements: dict
containers:
description:
- List of dict objects containing the basic information about each container. Keys matches the C(docker container ls)
output unless O(verbose_output=true). See description for O(verbose_output).
returned: When O(containers=true)
type: list
elements: dict
images:
description:
- List of dict objects containing the basic information about each image. Keys matches the C(docker image ls) output unless
O(verbose_output=true). See description for O(verbose_output).
returned: When O(images=true)
type: list
elements: dict
disk_usage:
description:
- Information on summary disk usage by images, containers and volumes on docker host unless O(verbose_output=true). See
description for O(verbose_output).
returned: When O(disk_usage=true)
type: dict
"""
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
APIError,
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
convert_filters,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
clean_dict_booleans_for_docker_api,
)
class DockerHostManager(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None:
super().__init__()
self.client = client
self.results = results
self.verbose_output = self.client.module.params["verbose_output"]
listed_objects = ["volumes", "networks", "containers", "images"]
self.results["host_info"] = self.get_docker_host_info()
# At this point we definitely know that we can talk to the Docker daemon
self.results["can_talk_to_docker"] = True
self.client.fail_results["can_talk_to_docker"] = True
if self.client.module.params["disk_usage"]:
self.results["disk_usage"] = self.get_docker_disk_usage_facts()
for docker_object in listed_objects:
if self.client.module.params[docker_object]:
returned_name = docker_object
filter_name = f"{docker_object}_filters"
filters = clean_dict_booleans_for_docker_api(
client.module.params.get(filter_name), allow_sequences=True
)
self.results[returned_name] = self.get_docker_items_list(
docker_object, filters
)
def get_docker_host_info(self) -> dict[str, t.Any]:
try:
return self.client.info()
except APIError as exc:
self.client.fail(f"Error inspecting docker host: {exc}")
def get_docker_disk_usage_facts(self) -> dict[str, t.Any]:
try:
if self.verbose_output:
return self.client.df()
return {"LayersSize": self.client.df()["LayersSize"]}
except APIError as exc:
self.client.fail(f"Error inspecting docker host: {exc}")
def get_docker_items_list(
self,
docker_object: str,
filters: dict[str, t.Any] | None = None,
verbose: bool = False,
) -> list[dict[str, t.Any]]:
items = []
header_containers = [
"Id",
"Image",
"Command",
"Created",
"Status",
"Ports",
"Names",
]
header_volumes = ["Driver", "Name"]
header_images = ["Id", "RepoTags", "Created", "Size"]
header_networks = ["Id", "Driver", "Name", "Scope"]
filter_arg = {}
if filters:
filter_arg["filters"] = filters
try:
if docker_object == "containers":
params = {
"limit": -1,
"all": 1 if self.client.module.params["containers_all"] else 0,
"size": 0,
"trunc_cmd": 0,
"filters": convert_filters(filters) if filters else None,
}
items = self.client.get_json("/containers/json", params=params)
elif docker_object == "networks":
params = {"filters": convert_filters(filters or {})}
items = self.client.get_json("/networks", params=params)
elif docker_object == "images":
params = {
"only_ids": 0,
"all": 0,
"filters": convert_filters(filters) if filters else None,
}
items = self.client.get_json("/images/json", params=params)
elif docker_object == "volumes":
params = {
"filters": convert_filters(filters) if filters else None,
}
items = self.client.get_json("/volumes", params=params)
items = items["Volumes"]
except APIError as exc:
self.client.fail(
f"Error inspecting docker host for object '{docker_object}': {exc}"
)
if self.verbose_output:
return items
items_list = []
for item in items:
item_record = {}
if docker_object == "containers":
for key in header_containers:
item_record[key] = item.get(key)
elif docker_object == "networks":
for key in header_networks:
item_record[key] = item.get(key)
elif docker_object == "images":
for key in header_images:
item_record[key] = item.get(key)
elif docker_object == "volumes":
for key in header_volumes:
item_record[key] = item.get(key)
items_list.append(item_record)
return items_list
def main() -> None:
argument_spec = {
"containers": {"type": "bool", "default": False},
"containers_all": {"type": "bool", "default": False},
"containers_filters": {"type": "dict"},
"images": {"type": "bool", "default": False},
"images_filters": {"type": "dict"},
"networks": {"type": "bool", "default": False},
"networks_filters": {"type": "dict"},
"volumes": {"type": "bool", "default": False},
"volumes_filters": {"type": "dict"},
"disk_usage": {"type": "bool", "default": False},
"verbose_output": {"type": "bool", "default": False},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
fail_results={
"can_talk_to_docker": False,
},
)
if (
client.module.params["api_version"] is None
or client.module.params["api_version"].lower() == "auto"
):
# At this point we know that we can talk to Docker, since we asked it for the API version
client.fail_results["can_talk_to_docker"] = True
try:
results = {
"changed": False,
}
DockerHostManager(client, results)
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,647 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_image_build
short_description: Build Docker images using Docker buildx
version_added: 3.6.0
description:
- This module allows you to build Docker images using Docker's buildx plugin (BuildKit).
- Note that the module is B(not idempotent) in the sense of classical Ansible modules. The only idempotence check is whether
the built image already exists. This check can be disabled with the O(rebuild) option.
extends_documentation_fragment:
- community.docker._docker.cli_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: full
diff_mode:
support: none
idempotent:
support: partial
details:
- If O(rebuild=always) the module is not idempotent.
options:
name:
description:
- 'Image name. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When pushing or
pulling an image the name can optionally include the tag by appending C(:tag_name).'
- Note that image IDs (hashes) and names with digest cannot be used.
type: str
required: true
tag:
description:
- Tag for the image name O(name) that is to be tagged.
- If O(name)'s format is C(name:tag), then the tag value from O(name) will take precedence.
type: str
default: latest
path:
description:
- The path for the build environment.
type: path
required: true
dockerfile:
description:
- Provide an alternate name for the Dockerfile to use when building an image.
- This can also include a relative path (relative to O(path)).
type: str
cache_from:
description:
- List of image names to consider as cache source.
type: list
elements: str
pull:
description:
- When building an image downloads any updates to the FROM image in Dockerfile.
type: bool
default: false
network:
description:
- The network to use for C(RUN) build instructions.
type: str
nocache:
description:
- Do not use cache when building an image.
type: bool
default: false
etc_hosts:
description:
- Extra hosts to add to C(/etc/hosts) in building containers, as a mapping of hostname to IP address.
- Instead of an IP address, the special value V(host-gateway) can also be used, which resolves to the host's gateway
IP and allows building containers to connect to services running on the host.
type: dict
args:
description:
- Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive.
- Docker expects the value to be a string. For convenience any non-string values will be converted to strings.
type: dict
target:
description:
- When building an image specifies an intermediate build stage by name as a final stage for the resulting image.
type: str
platform:
description:
- Platforms in the format C(os[/arch[/variant]]).
- Since community.docker 3.10.0 this can be a list of platforms, instead of just a single platform.
type: list
elements: str
shm_size:
description:
- Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer. Unit can be V(B) (byte), V(K) (kibibyte,
1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
- Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses V(64M).
type: str
labels:
description:
- Dictionary of key value pairs.
type: dict
rebuild:
description:
- Defines the behavior of the module if the image to build (as specified in O(name) and O(tag)) already exists.
type: str
choices:
- never
- always
default: never
secrets:
description:
- Secrets to expose to the build.
type: list
elements: dict
version_added: 3.10.0
suboptions:
id:
description:
- The secret identifier.
- The secret will be made available as a file in the container under C(/run/secrets/<id>).
type: str
required: true
type:
description:
- Type of the secret.
type: str
choices:
file:
- Reads the secret from a file on the target.
- The file must be specified in O(secrets[].src).
env:
- Reads the secret from an environment variable on the target.
- The environment variable must be named in O(secrets[].env).
- Note that this requires the Buildkit plugin to have version 0.6.0 or newer.
value:
- Provides the secret from a given value O(secrets[].value).
- B(Note) that the secret will be passed as an environment variable to C(docker compose). Use another mean of
transport if you consider this not safe enough.
- Note that this requires the Buildkit plugin to have version 0.6.0 or newer.
required: true
src:
description:
- Source path of the secret.
- Only supported and required for O(secrets[].type=file).
type: path
env:
description:
- Environment value of the secret.
- Only supported and required for O(secrets[].type=env).
type: str
value:
description:
- Value of the secret.
- B(Note) that the secret will be passed as an environment variable to C(docker compose). Use another mean of transport
if you consider this not safe enough.
- Only supported and required for O(secrets[].type=value).
type: str
outputs:
description:
- Output destinations.
- You can provide a list of exporters to export the built image in various places. Note that not all exporters might
be supported by the build driver used.
- Note that depending on how this option is used, no image with name O(name) and tag O(tag) might be created, which
can cause the basic idempotency this module offers to not work.
- Providing an empty list to this option is equivalent to not specifying it at all. The default behavior is a single
entry with O(outputs[].type=image).
- B(Note) that since community.docker 4.2.0, an entry for O(name)/O(tag) is added if O(outputs) has at least one entry
and no entry has type O(outputs[].type=image) and includes O(name)/O(tag) in O(outputs[].name). This is because the
module would otherwise pass C(--tag name:image) to the buildx plugin, which for some reason overwrites all images
in O(outputs) by the C(name:image) provided in O(name)/O(tag).
type: list
elements: dict
version_added: 3.10.0
suboptions:
type:
description:
- The type of exporter to use.
type: str
choices:
local:
- This export type writes all result files to a directory on the client. The new files will be owned by the current
user. On multi-platform builds, all results will be put in subdirectories by their platform.
- The destination has to be provided in O(outputs[].dest).
tar:
- This export type export type writes all result files as a single tarball on the client. On multi-platform builds,
all results will be put in subdirectories by their platform.
- The destination has to be provided in O(outputs[].dest).
oci:
- This export type writes the result image or manifest list as an L(OCI image layout,
https://github.com/opencontainers/image-spec/blob/v1.0.1/image-layout.md)
tarball on the client.
- The destination has to be provided in O(outputs[].dest).
docker:
- This export type writes the single-platform result image as a Docker image specification tarball on the client.
Tarballs created by this exporter are also OCI compatible.
- The destination can be provided in O(outputs[].dest). If not specified, the tar will be loaded automatically
to the local image store.
- The Docker context where to import the result can be provided in O(outputs[].context).
image:
- This exporter writes the build result as an image or a manifest list. When using this driver, the image will
appear in C(docker images).
- The image name can be provided in O(outputs[].name). If it is not provided, O(name) and O(tag) will be used.
- Optionally, image can be automatically pushed to a registry by setting O(outputs[].push=true).
required: true
dest:
description:
- The destination path.
- Required for O(outputs[].type=local), O(outputs[].type=tar), O(outputs[].type=oci).
- Optional for O(outputs[].type=docker).
type: path
context:
description:
- Name for the Docker context where to import the result.
- Optional for O(outputs[].type=docker).
type: str
name:
description:
- Name(s) under which the image is stored under.
- If not provided, O(name) and O(tag) will be used.
- Optional for O(outputs[].type=image).
- This can be a list of strings since community.docker 4.2.0.
type: list
elements: str
push:
description:
- Whether to push the built image to a registry.
- Only used for O(outputs[].type=image).
type: bool
default: false
requirements:
- "Docker CLI with Docker buildx plugin"
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_image_push
- module: community.docker.docker_image_tag
"""
EXAMPLES = r"""
---
- name: Build Python 3.12 image
community.docker.docker_image_build:
name: localhost/python/3.12:latest
path: /home/user/images/python
dockerfile: Dockerfile-3.12
- name: Build multi-platform image
community.docker.docker_image_build:
name: multi-platform-image
tag: "1.5.2"
path: /home/user/images/multi-platform
platform:
- linux/amd64
- linux/arm64/v8
"""
RETURN = r"""
image:
description: Image inspection results for the affected image.
returned: success
type: dict
sample: {}
command:
description: The command executed.
returned: success and for some failures
type: list
elements: str
version_added: 4.2.0
"""
import base64
import os
import traceback
import typing as t
from ansible.module_utils.common.text.converters import to_text
from ansible.module_utils.common.text.formatters import human_to_bytes
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
parse_repository_tag,
)
from ansible_collections.community.docker.plugins.module_utils._common_cli import (
AnsibleModuleDockerClient,
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
clean_dict_booleans_for_docker_api,
is_image_name_id,
is_valid_tag,
)
from ansible_collections.community.docker.plugins.module_utils._version import (
LooseVersion,
)
if t.TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule
def convert_to_bytes(
value: str | None,
module: AnsibleModule,
name: str,
unlimited_value: int | None = None,
) -> int | None:
if value is None:
return value
try:
if unlimited_value is not None and value in ("unlimited", str(unlimited_value)):
return unlimited_value
return human_to_bytes(value)
except ValueError as exc:
module.fail_json(msg=f"Failed to convert {name} to bytes: {exc}")
def dict_to_list(dictionary: dict[str, t.Any], concat: str = "=") -> list[str]:
return [f"{k}{concat}{v}" for k, v in sorted(dictionary.items())]
def _quote_csv(text: str) -> str:
if text.strip() == text and all(i not in text for i in '",\r\n'):
return text
text = text.replace('"', '""')
return f'"{text}"'
class ImageBuilder(DockerBaseClass):
def __init__(self, client: AnsibleModuleDockerClient) -> None:
super().__init__()
self.client = client
self.check_mode = self.client.check_mode
parameters = self.client.module.params
self.cache_from = parameters["cache_from"]
self.pull = parameters["pull"]
self.network = parameters["network"]
self.nocache = parameters["nocache"]
self.etc_hosts = clean_dict_booleans_for_docker_api(parameters["etc_hosts"])
self.args = clean_dict_booleans_for_docker_api(parameters["args"])
self.target = parameters["target"]
self.platform = parameters["platform"]
self.shm_size = convert_to_bytes(
parameters["shm_size"], self.client.module, "shm_size"
)
self.labels = clean_dict_booleans_for_docker_api(parameters["labels"])
self.rebuild = parameters["rebuild"]
self.secrets = parameters["secrets"]
self.outputs = parameters["outputs"]
buildx = self.client.get_client_plugin_info("buildx")
if buildx is None:
self.fail(
f"Docker CLI {self.client.get_cli()} does not have the buildx plugin installed"
)
buildx_version = buildx["Version"].lstrip("v")
if self.secrets:
for secret in self.secrets:
if secret["type"] in ("env", "value") and LooseVersion(
buildx_version
) < LooseVersion("0.6.0"):
self.fail(
f"The Docker buildx plugin has version {buildx_version}, but 0.6.0 is needed for secrets of type=env and type=value"
)
if (
self.outputs
and len(self.outputs) > 1
and LooseVersion(buildx_version) < LooseVersion("0.13.0")
):
self.fail(
f"The Docker buildx plugin has version {buildx_version}, but 0.13.0 is needed to specify more than one output"
)
self.path = parameters["path"]
if not os.path.isdir(self.path):
self.fail(f'"{self.path}" is not an existing directory')
self.dockerfile = parameters["dockerfile"]
if self.dockerfile and not os.path.isfile(
os.path.join(self.path, self.dockerfile)
):
self.fail(
f'"{os.path.join(self.path, self.dockerfile)}" is not an existing file'
)
self.name = parameters["name"]
self.tag = parameters["tag"]
if not is_valid_tag(self.tag, allow_empty=True):
self.fail(f'"{self.tag}" is not a valid docker tag')
if is_image_name_id(self.name):
self.fail("Image name must not be a digest")
# If name contains a tag, it takes precedence over tag parameter.
repo, repo_tag = parse_repository_tag(self.name)
if repo_tag:
self.name = repo
self.tag = repo_tag
if is_image_name_id(self.tag):
self.fail("Image name must not contain a digest, but have a tag")
if self.outputs:
found = False
name_tag = f"{self.name}:{self.tag}"
for output in self.outputs:
if output["type"] == "image":
if not output["name"]:
# Since we no longer pass --tag if --output is provided, we need to set this manually
output["name"] = [name_tag]
if output["name"] and name_tag in output["name"]:
found = True
if not found:
self.outputs.append(
{
"type": "image",
"name": [name_tag],
"push": False,
}
)
if LooseVersion(buildx_version) < LooseVersion("0.13.0"):
self.fail(
f"The output does not include an image with name {name_tag}, and the Docker"
f" buildx plugin has version {buildx_version} which only supports one output."
)
def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
self.client.fail(msg, **kwargs)
def add_list_arg(self, args: list[str], option: str, values: list[str]) -> None:
for value in values:
args.extend([option, value])
def add_args(self, args: list[str]) -> dict[str, t.Any]:
environ_update = {}
if not self.outputs:
args.extend(["--tag", f"{self.name}:{self.tag}"])
if self.dockerfile:
args.extend(["--file", os.path.join(self.path, self.dockerfile)])
if self.cache_from:
self.add_list_arg(args, "--cache-from", self.cache_from)
if self.pull:
args.append("--pull")
if self.network:
args.extend(["--network", self.network])
if self.nocache:
args.append("--no-cache")
if self.etc_hosts:
self.add_list_arg(args, "--add-host", dict_to_list(self.etc_hosts, ":"))
if self.args:
self.add_list_arg(args, "--build-arg", dict_to_list(self.args))
if self.target:
args.extend(["--target", self.target])
if self.platform:
for platform in self.platform:
args.extend(["--platform", platform])
if self.shm_size:
args.extend(["--shm-size", str(self.shm_size)])
if self.labels:
self.add_list_arg(args, "--label", dict_to_list(self.labels))
if self.secrets:
random_prefix = None
for index, secret in enumerate(self.secrets):
sid = secret["id"]
if secret["type"] == "file":
src = secret["src"]
args.extend(["--secret", f"id={sid},type=file,src={src}"])
if secret["type"] == "env":
env = secret["src"]
args.extend(["--secret", f"id={sid},type=env,env={env}"])
if secret["type"] == "value":
# We pass values on using environment variables. The user has been warned in the documentation
# that they should only use this mechanism when being comfortable with it.
if random_prefix is None:
# Use /dev/urandom to generate some entropy to make the environment variable's name unguessable
random_prefix = (
base64.b64encode(os.urandom(16))
.decode("utf-8")
.replace("=", "")
)
env_name = (
f"ANSIBLE_DOCKER_COMPOSE_ENV_SECRET_{random_prefix}_{index}"
)
environ_update[env_name] = secret["value"]
args.extend(["--secret", f"id={sid},type=env,env={env_name}"])
if self.outputs:
for output in self.outputs:
subargs = []
if output["type"] == "local":
dest = output["dest"]
subargs.extend(["type=local", f"dest={dest}"])
if output["type"] == "tar":
dest = output["dest"]
subargs.extend(["type=tar", f"dest={dest}"])
if output["type"] == "oci":
dest = output["dest"]
subargs.extend(["type=oci", f"dest={dest}"])
if output["type"] == "docker":
subargs.append("type=docker")
dest = output["dest"]
if output["dest"] is not None:
subargs.append(f"dest={dest}")
if output["context"] is not None:
context = output["context"]
subargs.append(f"context={context}")
if output["type"] == "image":
subargs.append("type=image")
if output["name"] is not None:
name = ",".join(output["name"])
subargs.append(f"name={name}")
if output["push"]:
subargs.append("push=true")
if subargs:
args.extend(
["--output", ",".join(_quote_csv(subarg) for subarg in subargs)]
)
return environ_update
def build_image(self) -> dict[str, t.Any]:
image = self.client.find_image(self.name, self.tag)
results: dict[str, t.Any] = {
"changed": False,
"actions": [],
"image": image or {},
}
if image and self.rebuild == "never":
return results
results["changed"] = True
if not self.check_mode:
args = ["buildx", "build", "--progress", "plain"]
environ_update = self.add_args(args)
args.extend(["--", self.path])
rc, stdout, stderr = self.client.call_cli(
*args, environ_update=environ_update
)
if rc != 0:
self.fail(
f"Building {self.name}:{self.tag} failed",
stdout=to_text(stdout),
stderr=to_text(stderr),
command=args,
)
results["stdout"] = to_text(stdout)
results["stderr"] = to_text(stderr)
results["image"] = self.client.find_image(self.name, self.tag) or {}
results["command"] = args
return results
def main() -> None:
argument_spec = {
"name": {"type": "str", "required": True},
"tag": {"type": "str", "default": "latest"},
"path": {"type": "path", "required": True},
"dockerfile": {"type": "str"},
"cache_from": {"type": "list", "elements": "str"},
"pull": {"type": "bool", "default": False},
"network": {"type": "str"},
"nocache": {"type": "bool", "default": False},
"etc_hosts": {"type": "dict"},
"args": {"type": "dict"},
"target": {"type": "str"},
"platform": {"type": "list", "elements": "str"},
"shm_size": {"type": "str"},
"labels": {"type": "dict"},
"rebuild": {"type": "str", "choices": ["never", "always"], "default": "never"},
"secrets": {
"type": "list",
"elements": "dict",
"options": {
"id": {"type": "str", "required": True},
"type": {
"type": "str",
"choices": ["file", "env", "value"],
"required": True,
},
"src": {"type": "path"},
"env": {"type": "str"},
"value": {"type": "str", "no_log": True},
},
"required_if": [
("type", "file", ["src"]),
("type", "env", ["env"]),
("type", "value", ["value"]),
],
"mutually_exclusive": [
("src", "env", "value"),
],
"no_log": False,
},
"outputs": {
"type": "list",
"elements": "dict",
"options": {
"type": {
"type": "str",
"choices": ["local", "tar", "oci", "docker", "image"],
"required": True,
},
"dest": {"type": "path"},
"context": {"type": "str"},
"name": {"type": "list", "elements": "str"},
"push": {"type": "bool", "default": False},
},
"required_if": [
("type", "local", ["dest"]),
("type", "tar", ["dest"]),
("type", "oci", ["dest"]),
],
"mutually_exclusive": [
("dest", "name"),
("dest", "push"),
("context", "name"),
("context", "push"),
],
},
}
client = AnsibleModuleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
needs_api_version=False,
)
try:
results = ImageBuilder(client).build_image()
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,303 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_image_export
short_description: Export (archive) Docker images
version_added: 3.7.0
description:
- Creates an archive (tarball) from one or more Docker images.
- This can be copied to another machine and loaded with M(community.docker.docker_image_load).
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: full
diff_mode:
support: none
idempotent:
support: partial
details:
- Whether the module is idempotent depends on the storage API used for images,
which determines how the image ID is computed. The idempotency check needs
that the image ID equals the ID stored in archive's C(manifest.json).
This seemed to have worked fine with the default storage backend up to Docker 28,
but seems to have changed in Docker 29.
options:
names:
description:
- 'One or more image names. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When
pushing or pulling an image the name can optionally include the tag by appending C(:tag_name).'
- Note that image IDs (hashes) can also be used.
type: list
elements: str
required: true
aliases:
- name
tag:
description:
- Tag for the image name O(name) that is to be tagged.
- If O(name)'s format is C(name:tag), then the tag value from O(name) will take precedence.
type: str
default: latest
path:
description:
- The C(.tar) file the image should be exported to.
type: path
force:
description:
- Export the image even if the C(.tar) file already exists and seems to contain the right image.
type: bool
default: false
requirements:
- "Docker API >= 1.25"
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_image
- module: community.docker.docker_image_info
- module: community.docker.docker_image_load
"""
EXAMPLES = r"""
---
- name: Export an image
community.docker.docker_image_export:
name: pacur/centos-7
path: /tmp/centos-7.tar
- name: Export multiple images
community.docker.docker_image_export:
names:
- hello-world:latest
- pacur/centos-7:latest
path: /tmp/various.tar
"""
RETURN = r"""
images:
description: Image inspection results for the affected images.
returned: success
type: list
elements: dict
sample: []
"""
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._api.constants import (
DEFAULT_DATA_CHUNK_SIZE,
)
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
parse_repository_tag,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._image_archive import (
ImageArchiveInvalidException,
api_image_id,
load_archived_image_manifest,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
is_image_name_id,
is_valid_tag,
)
class ImageExportManager(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient) -> None:
super().__init__()
self.client = client
parameters = self.client.module.params
self.check_mode = self.client.check_mode
self.path = parameters["path"]
self.force = parameters["force"]
self.tag = parameters["tag"]
if not is_valid_tag(self.tag, allow_empty=True):
self.fail(f'"{self.tag}" is not a valid docker tag')
# If name contains a tag, it takes precedence over tag parameter.
self.names = []
for name in parameters["names"]:
if is_image_name_id(name):
self.names.append({"id": name, "joined": name})
else:
repo, repo_tag = parse_repository_tag(name)
if not repo_tag:
repo_tag = self.tag
self.names.append(
{"name": repo, "tag": repo_tag, "joined": f"{repo}:{repo_tag}"}
)
if not self.names:
self.fail("At least one image name must be specified")
def fail(self, msg: str) -> t.NoReturn:
self.client.fail(msg)
def get_export_reason(self) -> str | None:
if self.force:
return "Exporting since force=true"
try:
archived_images = load_archived_image_manifest(self.path)
if archived_images is None:
return "Overwriting since no image is present in archive"
except ImageArchiveInvalidException as exc:
self.log(f"Unable to extract manifest summary from archive: {exc}")
return "Overwriting an unreadable archive file"
left_names = list(self.names)
for archived_image in archived_images:
found = False
for i, name in enumerate(left_names):
if (
name["id"] == api_image_id(archived_image.image_id)
and [name["joined"]] == archived_image.repo_tags
):
del left_names[i]
found = True
break
if not found:
return f"Overwriting archive since it contains unexpected image {archived_image.image_id} named {', '.join(archived_image.repo_tags)}"
if left_names:
return f"Overwriting archive since it is missing image(s) {', '.join([name['joined'] for name in left_names])}"
return None
def write_chunks(self, chunks: t.Generator[bytes]) -> None:
try:
with open(self.path, "wb") as fd:
for chunk in chunks:
fd.write(chunk)
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error writing image archive {self.path} - {exc}")
def export_images(self) -> None:
image_names = [name["joined"] for name in self.names]
image_names_str = ", ".join(image_names)
if len(image_names) == 1:
self.log(f"Getting archive of image {image_names[0]}")
try:
chunks = self.client._stream_raw_result(
self.client._get(
self.client._url("/images/{0}/get", image_names[0]), stream=True
),
chunk_size=DEFAULT_DATA_CHUNK_SIZE,
decode=False,
)
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error getting image {image_names[0]} - {exc}")
else:
self.log(f"Getting archive of images {image_names_str}")
try:
chunks = self.client._stream_raw_result(
self.client._get(
self.client._url("/images/get"),
stream=True,
params={"names": image_names},
),
chunk_size=DEFAULT_DATA_CHUNK_SIZE,
decode=False,
)
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error getting images {image_names_str} - {exc}")
self.write_chunks(chunks)
def run(self) -> dict[str, t.Any]:
tag = self.tag
if not tag:
tag = "latest"
images = []
for name in self.names:
if "id" in name:
image = self.client.find_image_by_id(
name["id"], accept_missing_image=True
)
else:
image = self.client.find_image(name=name["name"], tag=name["tag"])
if not image:
self.fail(f"Image {name['joined']} not found")
images.append(image)
# Will have a 'sha256:' prefix
name["id"] = image["Id"]
results = {
"changed": False,
"images": images,
}
reason = self.get_export_reason()
if reason is not None:
results["msg"] = reason
results["changed"] = True
if not self.check_mode:
self.export_images()
return results
def main() -> None:
argument_spec = {
"path": {"type": "path"},
"force": {"type": "bool", "default": False},
"names": {
"type": "list",
"elements": "str",
"required": True,
"aliases": ["name"],
},
"tag": {"type": "str", "default": "latest"},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
)
try:
results = ImageExportManager(client).run()
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,247 @@
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_image_info
short_description: Inspect docker images
description:
- Provide one or more image names, and the module will inspect each, returning an array of inspection results.
- If an image does not exist locally, it will not appear in the results. If you want to check whether an image exists locally,
you can call the module with the image name, then check whether the result list is empty (image does not exist) or has
one element (the image exists locally).
- The module will not attempt to pull images from registries. Use M(community.docker.docker_image) with O(community.docker.docker_image#module:source=pull)
to ensure an image is pulled.
notes:
- This module was called C(docker_image_facts) before Ansible 2.8. The usage did not change.
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
- community.docker._attributes.info_module
- community.docker._attributes.idempotent_not_modify_state
options:
name:
description:
- An image name or a list of image names. Name format will be C(name[:tag]) or C(repository/name[:tag]), where C(tag)
is optional. If a tag is not provided, V(latest) will be used. Instead of image names, also image IDs can be used.
- If no name is provided, a list of all images will be returned.
type: list
elements: str
requirements:
- "Docker API >= 1.25"
author:
- Chris Houseknecht (@chouseknecht)
"""
EXAMPLES = r"""
---
- name: Inspect a single image
community.docker.docker_image_info:
name: pacur/centos-7
- name: Inspect multiple images
community.docker.docker_image_info:
name:
- pacur/centos-7
- sinatra
register: result
- name: Make sure that both images pacur/centos-7 and sinatra exist locally
ansible.builtin.assert:
that:
- result.images | length == 2
"""
RETURN = r"""
images:
description:
- Inspection results for the selected images.
- The list only contains inspection results of images existing locally.
returned: always
type: list
elements: dict
sample: [
{
"Architecture": "amd64",
"Author": "",
"Comment": "",
"Config": {
"AttachStderr": false,
"AttachStdin": false,
"AttachStdout": false,
"Cmd": ["/etc/docker/registry/config.yml"],
"Domainname": "",
"Entrypoint": ["/bin/registry"],
"Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],
"ExposedPorts": {"5000/tcp": {}},
"Hostname": "e5c68db50333",
"Image": "c72dce2618dc8f7b794d2b2c2b1e64e0205ead5befc294f8111da23bd6a2c799",
"Labels": {},
"OnBuild": [],
"OpenStdin": false,
"StdinOnce": false,
"Tty": false,
"User": "",
"Volumes": {"/var/lib/registry": {}},
"WorkingDir": "",
},
"Container": "e83a452b8fb89d78a25a6739457050131ca5c863629a47639530d9ad2008d610",
"ContainerConfig": {
"AttachStderr": false,
"AttachStdin": false,
"AttachStdout": false,
"Cmd": ["/bin/sh", "-c", '#(nop) CMD ["/etc/docker/registry/config.yml"]'],
"Domainname": "",
"Entrypoint": ["/bin/registry"],
"Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],
"ExposedPorts": {"5000/tcp": {}},
"Hostname": "e5c68db50333",
"Image": "c72dce2618dc8f7b794d2b2c2b1e64e0205ead5befc294f8111da23bd6a2c799",
"Labels": {},
"OnBuild": [],
"OpenStdin": false,
"StdinOnce": false,
"Tty": false,
"User": "",
"Volumes": {"/var/lib/registry": {}},
"WorkingDir": "",
},
"Created": "2016-03-08T21:08:15.399680378Z",
"DockerVersion": "1.9.1",
"GraphDriver": {
"Data": null,
"Name": "aufs",
},
"Id": "53773d8552f07b730f3e19979e32499519807d67b344141d965463a950a66e08",
"Name": "registry:2",
"Os": "linux",
"Parent": "f0b1f729f784b755e7bf9c8c2e65d8a0a35a533769c2588f02895f6781ac0805",
"RepoDigests": [],
"RepoTags": ["registry:2"],
"Size": 0,
"VirtualSize": 165808884,
},
]
"""
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
DockerException,
NotFound,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
parse_repository_tag,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
is_image_name_id,
)
class ImageManager(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None:
super().__init__()
self.client = client
self.results = results
self.name = self.client.module.params.get("name")
self.log(f"Gathering facts for images: {self.name}")
if self.name:
self.results["images"] = self.get_facts()
else:
self.results["images"] = self.get_all_images()
def fail(self, msg: str) -> t.NoReturn:
self.client.fail(msg)
def get_facts(self) -> list[dict[str, t.Any]]:
"""
Lookup and inspect each image name found in the names parameter.
:returns array of image dictionaries
"""
results = []
names = self.name
if not isinstance(names, list):
names = [names]
for name in names:
if is_image_name_id(name):
self.log(f"Fetching image {name} (ID)")
image = self.client.find_image_by_id(name, accept_missing_image=True)
else:
repository, tag = parse_repository_tag(name)
if not tag:
tag = "latest"
self.log(f"Fetching image {repository}:{tag}")
image = self.client.find_image(name=repository, tag=tag)
if image:
results.append(image)
return results
def get_all_images(self) -> list[dict[str, t.Any]]:
results = []
params = {
"only_ids": 0,
"all": 0,
}
images = self.client.get_json("/images/json", params=params)
for image in images:
try:
inspection = self.client.get_json("/images/{0}/json", image["Id"])
except NotFound:
inspection = None
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting image {image['Id']} - {exc}")
results.append(inspection)
return results
def main() -> None:
argument_spec = {
"name": {"type": "list", "elements": "str"},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
)
try:
results = {"changed": False, "images": []}
ImageManager(client, results)
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,211 @@
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_image_load
short_description: Load docker image(s) from archives
version_added: 1.3.0
description:
- Load one or multiple Docker images from a C(.tar) archive, and return information on the loaded image(s).
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: none
diff_mode:
support: none
idempotent:
support: none
options:
path:
description:
- The path to the C(.tar) archive to load Docker image(s) from.
type: path
required: true
requirements:
- "Docker API >= 1.25"
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_image_export
- module: community.docker.docker_image_push
- module: community.docker.docker_image_remove
- module: community.docker.docker_image_tag
"""
EXAMPLES = r"""
---
- name: Load all image(s) from the given tar file
community.docker.docker_image_load:
path: /path/to/images.tar
register: result
- name: Print the loaded image names
ansible.builtin.debug:
msg: "Loaded the following images: {{ result.image_names | join(', ') }}"
"""
RETURN = r"""
image_names:
description: List of image names and IDs loaded from the archive.
returned: success
type: list
elements: str
sample:
- 'hello-world:latest'
- 'sha256:e004c2cc521c95383aebb1fb5893719aa7a8eae2e7a71f316a4410784edb00a9'
images:
description: Image inspection results for the loaded images.
returned: success
type: list
elements: dict
sample: []
"""
import errno
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
is_image_name_id,
)
class ImageManager(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None:
super().__init__()
self.client = client
self.results = results
parameters = self.client.module.params
self.check_mode = self.client.check_mode
self.path = parameters["path"]
self.load_images()
@staticmethod
def _extract_output_line(line: dict[str, t.Any], output: list[str]) -> None:
"""
Extract text line from stream output and, if found, adds it to output.
"""
if "stream" in line or "status" in line:
# Make sure we have a string (assuming that line['stream'] and
# line['status'] are either not defined, falsish, or a string)
text_line = line.get("stream") or line.get("status") or ""
output.extend(text_line.splitlines())
def load_images(self) -> None:
"""
Load images from a .tar archive
"""
# Load image(s) from file
load_output: list[str] = []
try:
self.log(f"Opening image {self.path}")
with open(self.path, "rb") as image_tar:
self.log(f"Loading images from {self.path}")
res = self.client._post(
self.client._url("/images/load"), data=image_tar, stream=True
)
for line in self.client._stream_helper(res, decode=True):
self.log(line, pretty_print=True)
self._extract_output_line(line, load_output)
except EnvironmentError as exc:
if exc.errno == errno.ENOENT:
self.client.fail(f"Error opening archive {self.path} - {exc}")
self.client.fail(
f"Error loading archive {self.path} - {exc}",
stdout="\n".join(load_output),
)
except Exception as exc: # pylint: disable=broad-exception-caught
self.client.fail(
f"Error loading archive {self.path} - {exc}",
stdout="\n".join(load_output),
)
# Collect loaded images
loaded_images = []
for line in load_output:
if line.startswith("Loaded image:"):
loaded_images.append(line[len("Loaded image:") :].strip())
if line.startswith("Loaded image ID:"):
loaded_images.append(line[len("Loaded image ID:") :].strip())
if not loaded_images:
self.client.fail(
"Detected no loaded images. Archive potentially corrupt?",
stdout="\n".join(load_output),
)
images = []
for image_name in loaded_images:
if is_image_name_id(image_name):
images.append(self.client.find_image_by_id(image_name))
elif ":" in image_name:
image_name, tag = image_name.rsplit(":", 1)
images.append(self.client.find_image(image_name, tag))
else:
self.client.module.warn(
f'Image name "{image_name}" is neither ID nor has a tag'
)
self.results["image_names"] = loaded_images
self.results["images"] = images
self.results["changed"] = True
self.results["stdout"] = "\n".join(load_output)
def main() -> None:
client = AnsibleDockerClient(
argument_spec={
"path": {"type": "path", "required": True},
},
supports_check_mode=False,
)
try:
results: dict[str, t.Any] = {
"image_names": [],
"images": [],
}
ImageManager(client, results)
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,233 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_image_pull
short_description: Pull Docker images from registries
version_added: 3.6.0
description:
- Pulls a Docker image from a registry.
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: partial
details:
- When trying to pull an image with O(pull=always), the module assumes this is always changed in check mode.
- When check mode is combined with diff mode, the pulled image's ID is always shown as V(unknown) in the diff.
diff_mode:
support: full
idempotent:
support: full
options:
name:
description:
- Image name. Name format must be one of V(name), V(repository/name), or V(registry_server:port/name).
- The name can optionally include the tag by appending V(:tag_name), or it can contain a digest by appending V(@hash:digest).
type: str
required: true
tag:
description:
- Used to select an image when pulling. Defaults to V(latest).
- If O(name) parameter format is C(name:tag) or C(image@hash:digest), then O(tag) will be ignored.
type: str
default: latest
platform:
description:
- Ask for this specific platform when pulling.
type: str
pull:
description:
- Determines when to pull an image.
- If V(always), will always pull the image.
- If V(not_present), will only pull the image if no image of the name exists on the current Docker daemon, or if O(platform)
does not match.
type: str
choices:
- always
- not_present
default: always
requirements:
- "Docker API >= 1.25"
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_image_pull
- module: community.docker.docker_image_remove
- module: community.docker.docker_image_tag
"""
EXAMPLES = r"""
---
- name: Pull an image
community.docker.docker_image_pull:
name: pacur/centos-7
# Select platform for pulling. If not specified, will pull whatever docker prefers.
platform: amd64
"""
RETURN = r"""
image:
description: Image inspection results for the affected image.
returned: success
type: dict
sample: {}
"""
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
parse_repository_tag,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._platform import (
compare_platform_strings,
compose_platform_string,
normalize_platform_string,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
is_image_name_id,
is_valid_tag,
)
def image_info(image: dict[str, t.Any] | None) -> dict[str, t.Any]:
result = {}
if image:
result["id"] = image["Id"]
else:
result["exists"] = False
return result
class ImagePuller(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient) -> None:
super().__init__()
self.client = client
self.check_mode = self.client.check_mode
parameters = self.client.module.params
self.name: str = parameters["name"]
self.tag: str = parameters["tag"]
self.platform: str | None = parameters["platform"]
self.pull_mode: t.Literal["always", "not_present"] = parameters["pull"]
if is_image_name_id(self.name):
self.client.fail("Cannot pull an image by ID")
if not is_valid_tag(self.tag, allow_empty=True):
self.client.fail(f'"{self.tag}" is not a valid docker tag!')
# If name contains a tag, it takes precedence over tag parameter.
repo, repo_tag = parse_repository_tag(self.name)
if repo_tag:
self.name = repo
self.tag = repo_tag
def pull(self) -> dict[str, t.Any]:
image = self.client.find_image(name=self.name, tag=self.tag)
actions: list[str] = []
diff = {"before": image_info(image), "after": image_info(image)}
results = {
"changed": False,
"actions": actions,
"image": image or {},
"diff": diff,
}
if image and self.pull_mode == "not_present":
if self.platform is None:
return results
host_info = self.client.info()
wanted_platform = normalize_platform_string(
self.platform,
daemon_os=host_info.get("OSType"),
daemon_arch=host_info.get("Architecture"),
)
image_platform = compose_platform_string(
os=image.get("Os"),
arch=image.get("Architecture"),
variant=image.get("Variant"),
daemon_os=host_info.get("OSType"),
daemon_arch=host_info.get("Architecture"),
)
if compare_platform_strings(wanted_platform, image_platform):
return results
actions.append(f"Pulled image {self.name}:{self.tag}")
if self.check_mode:
results["changed"] = True
diff["after"] = image_info({"Id": "unknown"})
else:
image, not_changed = self.client.pull_image(
self.name, tag=self.tag, image_platform=self.platform
)
results["image"] = image
results["changed"] = not not_changed
diff["after"] = image_info(image)
return results
def main() -> None:
argument_spec = {
"name": {"type": "str", "required": True},
"tag": {"type": "str", "default": "latest"},
"platform": {"type": "str"},
"pull": {
"type": "str",
"choices": ["always", "not_present"],
"default": "always",
},
}
option_minimal_versions = {
"platform": {"docker_api_version": "1.32"},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
option_minimal_versions=option_minimal_versions,
)
try:
results = ImagePuller(client).pull()
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,205 @@
#!/usr/bin/python
#
# Copyright (c) 2023, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_image_push
short_description: Push Docker images to registries
version_added: 3.6.0
description:
- Pushes a Docker image to a registry.
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: none
diff_mode:
support: none
idempotent:
support: full
options:
name:
description:
- Image name. Name format must be one of V(name), V(repository/name), or V(registry_server:port/name).
- The name can optionally include the tag by appending V(:tag_name), or it can contain a digest by appending V(@hash:digest).
type: str
required: true
tag:
description:
- Select which image to push. Defaults to V(latest).
- If O(name) parameter format is C(name:tag) or C(image@hash:digest), then O(tag) will be ignored.
type: str
default: latest
requirements:
- "Docker API >= 1.25"
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_image_pull
- module: community.docker.docker_image_remove
- module: community.docker.docker_image_tag
"""
EXAMPLES = r"""
---
- name: Push an image
community.docker.docker_image_push:
name: registry.example.com:5000/repo/image
tag: latest
"""
RETURN = r"""
image:
description: Image inspection results for the affected image.
returned: success
type: dict
sample: {}
"""
import base64
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._api.auth import (
get_config_header,
resolve_repository_name,
)
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
DockerException,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
parse_repository_tag,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
is_image_name_id,
is_valid_tag,
)
class ImagePusher(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient) -> None:
super().__init__()
self.client = client
self.check_mode = self.client.check_mode
parameters = self.client.module.params
self.name: str = parameters["name"]
self.tag: str = parameters["tag"]
if is_image_name_id(self.name):
self.client.fail("Cannot push an image by ID")
if not is_valid_tag(self.tag, allow_empty=True):
self.client.fail(f'"{self.tag}" is not a valid docker tag!')
# If name contains a tag, it takes precedence over tag parameter.
repo, repo_tag = parse_repository_tag(self.name)
if repo_tag:
self.name = repo
self.tag = repo_tag
if is_image_name_id(self.tag):
self.client.fail("Cannot push an image by digest")
if not is_valid_tag(self.tag, allow_empty=False):
self.client.fail(f'"{self.tag}" is not a valid docker tag!')
def push(self) -> dict[str, t.Any]:
image = self.client.find_image(name=self.name, tag=self.tag)
if not image:
self.client.fail(f"Cannot find image {self.name}:{self.tag}")
actions: list[str] = []
results: dict[str, t.Any] = {
"changed": False,
"actions": actions,
"image": image,
}
push_registry, push_repo = resolve_repository_name(self.name)
try:
actions.append(f"Pushed image {self.name}:{self.tag}")
headers = {}
header = get_config_header(self.client, push_registry)
if not header:
# For some reason, from Docker 28.3.3 on not specifying X-Registry-Auth seems to be invalid.
# See https://github.com/moby/moby/issues/50614.
header = base64.urlsafe_b64encode(b"{}")
headers["X-Registry-Auth"] = header
response = self.client._post_json(
self.client._url("/images/{0}/push", self.name),
data=None,
headers=headers,
stream=True,
params={"tag": self.tag},
)
self.client._raise_for_status(response)
for line in self.client._stream_helper(response, decode=True):
self.log(line, pretty_print=True)
if line.get("errorDetail"):
raise RuntimeError(line["errorDetail"]["message"])
status = line.get("status")
if status in ("Pushing", "Pushed"):
results["changed"] = True
except Exception as exc: # pylint: disable=broad-exception-caught
if "unauthorized" in str(exc):
if "authentication required" in str(exc):
self.client.fail(
f"Error pushing image {push_registry}/{push_repo}:{self.tag} - {exc}. Try logging into {push_registry} first."
)
else:
self.client.fail(
f"Error pushing image {push_registry}/{push_repo}:{self.tag} - {exc}. Does the repository exist?"
)
self.client.fail(f"Error pushing image {self.name}:{self.tag}: {exc}")
return results
def main() -> None:
argument_spec = {
"name": {"type": "str", "required": True},
"tag": {"type": "str", "default": "latest"},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=False,
)
try:
results = ImagePusher(client).push()
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,292 @@
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
DOCUMENTATION = r"""
module: docker_image_remove
short_description: Remove Docker images
version_added: 3.6.0
description:
- Remove Docker images from the Docker daemon.
extends_documentation_fragment:
- community.docker._docker.api_documentation
- community.docker._attributes
- community.docker._attributes.actiongroup_docker
attributes:
check_mode:
support: full
diff_mode:
support: full
idempotent:
support: full
options:
name:
description:
- 'Image name. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When pushing or
pulling an image the name can optionally include the tag by appending C(:tag_name).'
- Note that image IDs (hashes) can also be used.
type: str
required: true
tag:
description:
- Tag for the image name O(name) that is to be tagged.
- If O(name)'s format is C(name:tag), then the tag value from O(name) will take precedence.
type: str
default: latest
force:
description:
- Un-tag and remove all images matching the specified name.
type: bool
default: false
prune:
description:
- Delete untagged parent images.
type: bool
default: true
requirements:
- "Docker API >= 1.25"
author:
- Felix Fontein (@felixfontein)
seealso:
- module: community.docker.docker_image_load
- module: community.docker.docker_image_pull
- module: community.docker.docker_image_tag
"""
EXAMPLES = r"""
---
- name: Remove an image
community.docker.docker_image_remove:
name: pacur/centos-7
"""
RETURN = r"""
image:
description:
- Image inspection results for the affected image before removal.
- Empty if the image was not found.
returned: success
type: dict
sample: {}
deleted:
description:
- The digests of the images that were deleted.
returned: success
type: list
elements: str
sample: []
untagged:
description:
- The digests of the images that were untagged.
returned: success
type: list
elements: str
sample: []
"""
import traceback
import typing as t
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
DockerException,
NotFound,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
parse_repository_tag,
)
from ansible_collections.community.docker.plugins.module_utils._common_api import (
AnsibleDockerClient,
RequestException,
)
from ansible_collections.community.docker.plugins.module_utils._util import (
DockerBaseClass,
is_image_name_id,
is_valid_tag,
)
class ImageRemover(DockerBaseClass):
def __init__(self, client: AnsibleDockerClient) -> None:
super().__init__()
self.client = client
self.check_mode = self.client.check_mode
self.diff = self.client.module._diff
parameters = self.client.module.params
self.name = parameters["name"]
self.tag = parameters["tag"]
self.force = parameters["force"]
self.prune = parameters["prune"]
if not is_valid_tag(self.tag, allow_empty=True):
self.fail(f'"{self.tag}" is not a valid docker tag')
# If name contains a tag, it takes precedence over tag parameter.
if not is_image_name_id(self.name):
repo, repo_tag = parse_repository_tag(self.name)
if repo_tag:
self.name = repo
self.tag = repo_tag
def fail(self, msg: str) -> t.NoReturn:
self.client.fail(msg)
def get_diff_state(self, image: dict[str, t.Any] | None) -> dict[str, t.Any]:
if not image:
return {"exists": False}
return {
"exists": True,
"id": image["Id"],
"tags": sorted(image.get("RepoTags") or []),
"digests": sorted(image.get("RepoDigests") or []),
}
def absent(self) -> dict[str, t.Any]:
actions: list[str] = []
deleted: list[str] = []
untagged: list[str] = []
results: dict[str, t.Any] = {
"changed": False,
"actions": actions,
"image": {},
"deleted": deleted,
"untagged": untagged,
}
name = self.name
if is_image_name_id(name):
image = self.client.find_image_by_id(name, accept_missing_image=True)
else:
image = self.client.find_image(name, self.tag)
if self.tag:
name = f"{self.name}:{self.tag}"
diff: dict[str, t.Any] = {}
if self.diff:
results["diff"] = diff
diff["before"] = self.get_diff_state(image)
if not image:
if self.diff:
diff["after"] = self.get_diff_state(image)
return results
results["changed"] = True
actions.append(f"Removed image {name}")
results["image"] = image
if not self.check_mode:
try:
res = self.client.delete_json(
"/images/{0}",
name,
params={"force": self.force, "noprune": not self.prune},
)
except NotFound:
# If the image vanished while we were trying to remove it, do not fail
res = []
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error removing image {name} - {exc}")
for entry in res:
if entry.get("Untagged"):
untagged.append(entry["Untagged"])
if entry.get("Deleted"):
deleted.append(entry["Deleted"])
untagged[:] = sorted(untagged)
deleted[:] = sorted(deleted)
if self.diff:
image_after = self.client.find_image_by_id(
image["Id"], accept_missing_image=True
)
diff["after"] = self.get_diff_state(image_after)
elif is_image_name_id(name):
deleted.append(image["Id"])
# TODO: the following is no longer correct with Docker 29+...
untagged[:] = sorted(
(image.get("RepoTags") or []) + (image.get("RepoDigests") or [])
)
if not self.force and results["untagged"]:
self.fail(
"Cannot delete image by ID that is still in use - use force=true"
)
if self.diff:
diff["after"] = self.get_diff_state({})
elif is_image_name_id(self.tag):
untagged.append(name)
if (
len(image.get("RepoTags") or []) < 1
and len(image.get("RepoDigests") or []) < 2
):
deleted.append(image["Id"])
if self.diff:
diff["after"] = self.get_diff_state(image)
try:
diff["after"]["digests"].remove(name)
except ValueError:
pass
else:
untagged.append(name)
if (
len(image.get("RepoTags") or []) < 2
and len(image.get("RepoDigests") or []) < 1
):
deleted.append(image["Id"])
if self.diff:
diff["after"] = self.get_diff_state(image)
try:
diff["after"]["tags"].remove(name)
except ValueError:
pass
return results
def main() -> None:
argument_spec = {
"name": {"type": "str", "required": True},
"tag": {"type": "str", "default": "latest"},
"force": {"type": "bool", "default": False},
"prune": {"type": "bool", "default": True},
}
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
)
try:
results = ImageRemover(client).absent()
client.module.exit_json(**results)
except DockerException as e:
client.fail(
f"An unexpected Docker error occurred: {e}",
exception=traceback.format_exc(),
)
except RequestException as e:
client.fail(
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
exception=traceback.format_exc(),
)
if __name__ == "__main__":
main()

Some files were not shown because too many files have changed in this diff Show more