| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2023, Felix Fontein <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: docker_image_push |
| 11 |
|
| 12 |
short_description: Push Docker images to registries |
| 13 |
|
| 14 |
version_added: 3.6.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- Pushes a Docker image to a registry. |
| 18 |
extends_documentation_fragment: |
| 19 |
- community.docker._docker.api_documentation |
| 20 |
- community.docker._attributes |
| 21 |
- community.docker._attributes.actiongroup_docker |
| 22 |
|
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: none |
| 26 |
diff_mode: |
| 27 |
support: none |
| 28 |
idempotent: |
| 29 |
support: full |
| 30 |
|
| 31 |
options: |
| 32 |
name: |
| 33 |
description: |
| 34 |
- Image name. Name format must be one of V(name), V(repository/name), or V(registry_server:port/name). |
| 35 |
- The name can optionally include the tag by appending V(:tag_name), or it can contain a digest by appending V(@hash:digest). |
| 36 |
type: str |
| 37 |
required: true |
| 38 |
tag: |
| 39 |
description: |
| 40 |
- Select which image to push. Defaults to V(latest). |
| 41 |
- If O(name) parameter format is C(name:tag) or C(image@hash:digest), then O(tag) will be ignored. |
| 42 |
type: str |
| 43 |
default: latest |
| 44 |
|
| 45 |
requirements: |
| 46 |
- "Docker API >= 1.25" |
| 47 |
|
| 48 |
author: |
| 49 |
- Felix Fontein (@felixfontein) |
| 50 |
|
| 51 |
seealso: |
| 52 |
- module: community.docker.docker_image_pull |
| 53 |
- module: community.docker.docker_image_remove |
| 54 |
- module: community.docker.docker_image_tag |
| 55 |
""" |
| 56 |
|
| 57 |
EXAMPLES = r""" |
| 58 |
--- |
| 59 |
- name: Push an image |
| 60 |
community.docker.docker_image_push: |
| 61 |
name: registry.example.com:5000/repo/image |
| 62 |
tag: latest |
| 63 |
""" |
| 64 |
|
| 65 |
RETURN = r""" |
| 66 |
image: |
| 67 |
description: Image inspection results for the affected image. |
| 68 |
returned: success |
| 69 |
type: dict |
| 70 |
sample: {} |
| 71 |
""" |
| 72 |
|
| 73 |
import base64 |
| 74 |
import traceback |
| 75 |
import typing as t |
| 76 |
|
| 77 |
from ansible_collections.community.docker.plugins.module_utils._api.auth import ( |
| 78 |
get_config_header, |
| 79 |
resolve_repository_name, |
| 80 |
) |
| 81 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 82 |
DockerException, |
| 83 |
) |
| 84 |
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import ( |
| 85 |
parse_repository_tag, |
| 86 |
) |
| 87 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 88 |
AnsibleDockerClient, |
| 89 |
RequestException, |
| 90 |
) |
| 91 |
from ansible_collections.community.docker.plugins.module_utils._util import ( |
| 92 |
DockerBaseClass, |
| 93 |
is_image_name_id, |
| 94 |
is_valid_tag, |
| 95 |
) |
| 96 |
|
| 97 |
|
| 98 |
class ImagePusher(DockerBaseClass): |
| 99 |
def __init__(self, client: AnsibleDockerClient) -> None: |
| 100 |
super().__init__() |
| 101 |
|
| 102 |
self.client = client |
| 103 |
self.check_mode = self.client.check_mode |
| 104 |
|
| 105 |
parameters = self.client.module.params |
| 106 |
self.name: str = parameters["name"] |
| 107 |
self.tag: str = parameters["tag"] |
| 108 |
|
| 109 |
if is_image_name_id(self.name): |
| 110 |
self.client.fail("Cannot push an image by ID") |
| 111 |
if not is_valid_tag(self.tag, allow_empty=True): |
| 112 |
self.client.fail(f'"{self.tag}" is not a valid docker tag!') |
| 113 |
|
| 114 |
# If name contains a tag, it takes precedence over tag parameter. |
| 115 |
repo, repo_tag = parse_repository_tag(self.name) |
| 116 |
if repo_tag: |
| 117 |
self.name = repo |
| 118 |
self.tag = repo_tag |
| 119 |
|
| 120 |
if is_image_name_id(self.tag): |
| 121 |
self.client.fail("Cannot push an image by digest") |
| 122 |
if not is_valid_tag(self.tag, allow_empty=False): |
| 123 |
self.client.fail(f'"{self.tag}" is not a valid docker tag!') |
| 124 |
|
| 125 |
def push(self) -> dict[str, t.Any]: |
| 126 |
image = self.client.find_image(name=self.name, tag=self.tag) |
| 127 |
if not image: |
| 128 |
self.client.fail(f"Cannot find image {self.name}:{self.tag}") |
| 129 |
|
| 130 |
actions: list[str] = [] |
| 131 |
results: dict[str, t.Any] = { |
| 132 |
"changed": False, |
| 133 |
"actions": actions, |
| 134 |
"image": image, |
| 135 |
} |
| 136 |
|
| 137 |
push_registry, push_repo = resolve_repository_name(self.name) |
| 138 |
try: |
| 139 |
actions.append(f"Pushed image {self.name}:{self.tag}") |
| 140 |
|
| 141 |
headers = {} |
| 142 |
header = get_config_header(self.client, push_registry) |
| 143 |
if not header: |
| 144 |
# For some reason, from Docker 28.3.3 on not specifying X-Registry-Auth seems to be invalid. |
| 145 |
# See https://github.com/moby/moby/issues/50614. |
| 146 |
header = base64.urlsafe_b64encode(b"{}") |
| 147 |
headers["X-Registry-Auth"] = header |
| 148 |
response = self.client._post_json( |
| 149 |
self.client._url("/images/{0}/push", self.name), |
| 150 |
data=None, |
| 151 |
headers=headers, |
| 152 |
stream=True, |
| 153 |
params={"tag": self.tag}, |
| 154 |
) |
| 155 |
self.client._raise_for_status(response) |
| 156 |
for line in self.client._stream_helper(response, decode=True): |
| 157 |
self.log(line, pretty_print=True) |
| 158 |
if line.get("errorDetail"): |
| 159 |
raise RuntimeError(line["errorDetail"]["message"]) |
| 160 |
status = line.get("status") |
| 161 |
if status in ("Pushing", "Pushed"): |
| 162 |
results["changed"] = True |
| 163 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 164 |
if "unauthorized" in str(exc): |
| 165 |
if "authentication required" in str(exc): |
| 166 |
self.client.fail( |
| 167 |
f"Error pushing image {push_registry}/{push_repo}:{self.tag} - {exc}. Try logging into {push_registry} first." |
| 168 |
) |
| 169 |
else: |
| 170 |
self.client.fail( |
| 171 |
f"Error pushing image {push_registry}/{push_repo}:{self.tag} - {exc}. Does the repository exist?" |
| 172 |
) |
| 173 |
self.client.fail(f"Error pushing image {self.name}:{self.tag}: {exc}") |
| 174 |
|
| 175 |
return results |
| 176 |
|
| 177 |
|
| 178 |
def main() -> None: |
| 179 |
argument_spec = { |
| 180 |
"name": {"type": "str", "required": True}, |
| 181 |
"tag": {"type": "str", "default": "latest"}, |
| 182 |
} |
| 183 |
|
| 184 |
client = AnsibleDockerClient( |
| 185 |
argument_spec=argument_spec, |
| 186 |
supports_check_mode=False, |
| 187 |
) |
| 188 |
|
| 189 |
try: |
| 190 |
results = ImagePusher(client).push() |
| 191 |
client.module.exit_json(**results) |
| 192 |
except DockerException as e: |
| 193 |
client.fail( |
| 194 |
f"An unexpected Docker error occurred: {e}", |
| 195 |
exception=traceback.format_exc(), |
| 196 |
) |
| 197 |
except RequestException as e: |
| 198 |
client.fail( |
| 199 |
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}", |
| 200 |
exception=traceback.format_exc(), |
| 201 |
) |
| 202 |
|
| 203 |
|
| 204 |
if __name__ == "__main__": |
| 205 |
main() |