| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2016 Olaf Kilian <[email protected]> |
| 4 |
# Chris Houseknecht, <[email protected]> |
| 5 |
# James Tanner, <[email protected]> |
| 6 |
# |
| 7 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 8 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
DOCUMENTATION = r""" |
| 13 |
module: docker_login |
| 14 |
short_description: Log into a Docker registry |
| 15 |
description: |
| 16 |
- Provides functionality similar to the C(docker login) command. |
| 17 |
- Authenticate with a docker registry and add the credentials to your local Docker config file respectively the credentials |
| 18 |
store associated to the registry. Adding the credentials to the config files resp. the credential store allows future |
| 19 |
connections to the registry using tools such as Ansible's Docker modules, the Docker CLI and Docker SDK for Python without |
| 20 |
needing to provide credentials. |
| 21 |
- Running in check mode will perform the authentication without updating the config file. |
| 22 |
extends_documentation_fragment: |
| 23 |
- community.docker._docker.api_documentation |
| 24 |
- community.docker._attributes |
| 25 |
- community.docker._attributes.actiongroup_docker |
| 26 |
|
| 27 |
attributes: |
| 28 |
check_mode: |
| 29 |
support: full |
| 30 |
diff_mode: |
| 31 |
support: none |
| 32 |
idempotent: |
| 33 |
support: full |
| 34 |
|
| 35 |
options: |
| 36 |
registry_url: |
| 37 |
description: |
| 38 |
- The registry URL. |
| 39 |
type: str |
| 40 |
default: "https://index.docker.io/v1/" |
| 41 |
aliases: |
| 42 |
- registry |
| 43 |
- url |
| 44 |
username: |
| 45 |
description: |
| 46 |
- The username for the registry account. |
| 47 |
- Required when O(state=present). |
| 48 |
type: str |
| 49 |
password: |
| 50 |
description: |
| 51 |
- The plaintext password for the registry account. |
| 52 |
- Required when O(state=present). |
| 53 |
type: str |
| 54 |
reauthorize: |
| 55 |
description: |
| 56 |
- Refresh existing authentication found in the configuration file. |
| 57 |
type: bool |
| 58 |
default: false |
| 59 |
aliases: |
| 60 |
- reauth |
| 61 |
config_path: |
| 62 |
description: |
| 63 |
- Custom path to the Docker CLI configuration file. |
| 64 |
type: path |
| 65 |
default: ~/.docker/config.json |
| 66 |
aliases: |
| 67 |
- dockercfg_path |
| 68 |
state: |
| 69 |
description: |
| 70 |
- This controls the current state of the user. V(present) will login in a user, V(absent) will log them out. |
| 71 |
- To logout you only need the registry server, which defaults to DockerHub. |
| 72 |
- Before 2.1 you could ONLY log in. |
| 73 |
- Docker does not support 'logout' with a custom config file. |
| 74 |
type: str |
| 75 |
default: 'present' |
| 76 |
choices: ['present', 'absent'] |
| 77 |
|
| 78 |
requirements: |
| 79 |
- "Docker API >= 1.25" |
| 80 |
author: |
| 81 |
- Olaf Kilian (@olsaki) <[email protected]> |
| 82 |
- Chris Houseknecht (@chouseknecht) |
| 83 |
""" |
| 84 |
|
| 85 |
EXAMPLES = r""" |
| 86 |
--- |
| 87 |
- name: Log into DockerHub |
| 88 |
community.docker.docker_login: |
| 89 |
username: docker |
| 90 |
password: rekcod |
| 91 |
|
| 92 |
- name: Log into private registry and force re-authorization |
| 93 |
community.docker.docker_login: |
| 94 |
registry_url: your.private.registry.io |
| 95 |
username: yourself |
| 96 |
password: secrets3 |
| 97 |
reauthorize: true |
| 98 |
|
| 99 |
- name: Log into DockerHub using a custom config file |
| 100 |
community.docker.docker_login: |
| 101 |
username: docker |
| 102 |
password: rekcod |
| 103 |
config_path: /tmp/.mydockercfg |
| 104 |
|
| 105 |
- name: Log out of DockerHub |
| 106 |
community.docker.docker_login: |
| 107 |
state: absent |
| 108 |
""" |
| 109 |
|
| 110 |
RETURN = r""" |
| 111 |
login_result: |
| 112 |
description: Result from the login. |
| 113 |
returned: when O(state=present) |
| 114 |
type: dict |
| 115 |
sample: {"serveraddress": "localhost:5000", "username": "testuser"} |
| 116 |
""" |
| 117 |
|
| 118 |
import base64 |
| 119 |
import json |
| 120 |
import os |
| 121 |
import traceback |
| 122 |
import typing as t |
| 123 |
|
| 124 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 125 |
|
| 126 |
from ansible_collections.community.docker.plugins.module_utils._api import auth |
| 127 |
from ansible_collections.community.docker.plugins.module_utils._api.auth import ( |
| 128 |
decode_auth, |
| 129 |
) |
| 130 |
from ansible_collections.community.docker.plugins.module_utils._api.credentials.errors import ( |
| 131 |
CredentialsNotFound, |
| 132 |
) |
| 133 |
from ansible_collections.community.docker.plugins.module_utils._api.credentials.store import ( |
| 134 |
Store, |
| 135 |
) |
| 136 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 137 |
DockerException, |
| 138 |
) |
| 139 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 140 |
AnsibleDockerClient, |
| 141 |
RequestException, |
| 142 |
) |
| 143 |
from ansible_collections.community.docker.plugins.module_utils._util import ( |
| 144 |
DEFAULT_DOCKER_REGISTRY, |
| 145 |
DockerBaseClass, |
| 146 |
) |
| 147 |
|
| 148 |
|
| 149 |
class DockerFileStore: |
| 150 |
""" |
| 151 |
A custom credential store class that implements only the functionality we need to |
| 152 |
update the docker config file when no credential helpers is provided. |
| 153 |
""" |
| 154 |
|
| 155 |
program = "<legacy config>" |
| 156 |
|
| 157 |
def __init__(self, config_path: str) -> None: |
| 158 |
self._config_path = config_path |
| 159 |
|
| 160 |
# Make sure we have a minimal config if none is available. |
| 161 |
self._config: dict[str, t.Any] = {"auths": {}} |
| 162 |
|
| 163 |
try: |
| 164 |
# Attempt to read the existing config. |
| 165 |
with open(self._config_path, "rt", encoding="utf-8") as f: |
| 166 |
config = json.load(f) |
| 167 |
except (ValueError, IOError): |
| 168 |
# No config found or an invalid config found so we'll ignore it. |
| 169 |
config = {} |
| 170 |
|
| 171 |
# Update our internal config with what ever was loaded. |
| 172 |
self._config.update(config) |
| 173 |
|
| 174 |
@property |
| 175 |
def config_path(self) -> str: |
| 176 |
""" |
| 177 |
Return the config path configured in this DockerFileStore instance. |
| 178 |
""" |
| 179 |
|
| 180 |
return self._config_path |
| 181 |
|
| 182 |
def get(self, server: str) -> dict[str, t.Any]: |
| 183 |
""" |
| 184 |
Retrieve credentials for `server` if there are any in the config file. |
| 185 |
Otherwise raise a `StoreError` |
| 186 |
""" |
| 187 |
|
| 188 |
server_creds = self._config["auths"].get(server) |
| 189 |
if not server_creds: |
| 190 |
raise CredentialsNotFound("No matching credentials") |
| 191 |
|
| 192 |
username, password = decode_auth(server_creds["auth"]) |
| 193 |
|
| 194 |
return {"Username": username, "Secret": password} |
| 195 |
|
| 196 |
def _write(self) -> None: |
| 197 |
""" |
| 198 |
Write config back out to disk. |
| 199 |
""" |
| 200 |
# Make sure directory exists |
| 201 |
directory = os.path.dirname(self._config_path) |
| 202 |
if not os.path.exists(directory): |
| 203 |
os.makedirs(directory) |
| 204 |
# Write config; make sure it has permissions 0x600 |
| 205 |
content = json.dumps(self._config, indent=4, sort_keys=True).encode("utf-8") |
| 206 |
f = os.open(self._config_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) |
| 207 |
try: |
| 208 |
os.write(f, content) |
| 209 |
finally: |
| 210 |
os.close(f) |
| 211 |
|
| 212 |
def store(self, server: str, username: str, password: str) -> None: |
| 213 |
""" |
| 214 |
Add a credentials for `server` to the current configuration. |
| 215 |
""" |
| 216 |
|
| 217 |
b64auth = base64.b64encode(to_bytes(username) + b":" + to_bytes(password)) |
| 218 |
tauth = to_text(b64auth) |
| 219 |
|
| 220 |
# build up the auth structure |
| 221 |
if "auths" not in self._config: |
| 222 |
self._config["auths"] = {} |
| 223 |
|
| 224 |
self._config["auths"][server] = {"auth": tauth} |
| 225 |
|
| 226 |
self._write() |
| 227 |
|
| 228 |
def erase(self, server: str) -> None: |
| 229 |
""" |
| 230 |
Remove credentials for the given server from the configuration. |
| 231 |
""" |
| 232 |
|
| 233 |
if "auths" in self._config and server in self._config["auths"]: |
| 234 |
self._config["auths"].pop(server) |
| 235 |
self._write() |
| 236 |
|
| 237 |
|
| 238 |
class LoginManager(DockerBaseClass): |
| 239 |
def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None: |
| 240 |
super().__init__() |
| 241 |
|
| 242 |
self.client = client |
| 243 |
self.results = results |
| 244 |
parameters = self.client.module.params |
| 245 |
self.check_mode = self.client.check_mode |
| 246 |
|
| 247 |
self.registry_url: str = parameters.get("registry_url") |
| 248 |
self.username: str | None = parameters.get("username") |
| 249 |
self.password: str | None = parameters.get("password") |
| 250 |
self.reauthorize: bool = parameters.get("reauthorize") |
| 251 |
self.config_path: str = parameters.get("config_path") |
| 252 |
self.state: t.Literal["present", "absent"] = parameters.get("state") |
| 253 |
|
| 254 |
def run(self) -> None: |
| 255 |
""" |
| 256 |
Do the actual work of this task here. This allows instantiation for partial |
| 257 |
testing. |
| 258 |
""" |
| 259 |
|
| 260 |
if self.state == "present": |
| 261 |
self.login() |
| 262 |
else: |
| 263 |
self.logout() |
| 264 |
|
| 265 |
def fail(self, msg: str) -> t.NoReturn: |
| 266 |
self.client.fail(msg) |
| 267 |
|
| 268 |
def _login(self, reauth: bool) -> dict[str, t.Any]: |
| 269 |
if self.config_path and os.path.exists(self.config_path): |
| 270 |
self.client._auth_configs = auth.load_config( |
| 271 |
self.config_path, credstore_env=self.client.credstore_env |
| 272 |
) |
| 273 |
elif not self.client._auth_configs or self.client._auth_configs.is_empty: |
| 274 |
self.client._auth_configs = auth.load_config( |
| 275 |
credstore_env=self.client.credstore_env |
| 276 |
) |
| 277 |
|
| 278 |
authcfg = self.client._auth_configs.resolve_authconfig(self.registry_url) |
| 279 |
# If we found an existing auth config for this registry and username |
| 280 |
# combination, we can return it immediately unless reauth is requested. |
| 281 |
if authcfg and authcfg.get("username") == self.username and not reauth: |
| 282 |
return authcfg |
| 283 |
|
| 284 |
req_data = { |
| 285 |
"username": self.username, |
| 286 |
"password": self.password, |
| 287 |
"email": None, |
| 288 |
"serveraddress": self.registry_url, |
| 289 |
} |
| 290 |
|
| 291 |
response = self.client._post_json(self.client._url("/auth"), data=req_data) |
| 292 |
if response.status_code == 200: |
| 293 |
self.client._auth_configs.add_auth( |
| 294 |
self.registry_url or auth.INDEX_NAME, req_data |
| 295 |
) |
| 296 |
return self.client._result(response, get_json=True) |
| 297 |
|
| 298 |
def login(self) -> None: |
| 299 |
""" |
| 300 |
Log into the registry with provided username/password. On success update the config |
| 301 |
file with the new authorization. |
| 302 |
|
| 303 |
:return: None |
| 304 |
""" |
| 305 |
|
| 306 |
self.results["actions"].append(f"Logged into {self.registry_url}") |
| 307 |
self.log(f"Log into {self.registry_url} with username {self.username}") |
| 308 |
try: |
| 309 |
response = self._login(self.reauthorize) |
| 310 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 311 |
self.fail( |
| 312 |
f"Logging into {self.registry_url} for user {self.username} failed - {exc}" |
| 313 |
) |
| 314 |
|
| 315 |
# If user is already logged in, then response contains password for user |
| 316 |
if "password" in response: |
| 317 |
# This returns correct password if user is logged in and wrong password is given. |
| 318 |
# So if it returns another password as we passed, and the user did not request to |
| 319 |
# reauthorize, still do it. |
| 320 |
if not self.reauthorize and response["password"] != self.password: |
| 321 |
try: |
| 322 |
response = self._login(True) |
| 323 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 324 |
self.fail( |
| 325 |
f"Logging into {self.registry_url} for user {self.username} failed - {exc}" |
| 326 |
) |
| 327 |
response.pop("password", None) |
| 328 |
self.results["login_result"] = response |
| 329 |
|
| 330 |
self.update_credentials() |
| 331 |
|
| 332 |
def logout(self) -> None: |
| 333 |
""" |
| 334 |
Log out of the registry. On success update the config file. |
| 335 |
|
| 336 |
:return: None |
| 337 |
""" |
| 338 |
|
| 339 |
# Get the configuration store. |
| 340 |
store = self.get_credential_store_instance(self.registry_url, self.config_path) |
| 341 |
|
| 342 |
try: |
| 343 |
store.get(self.registry_url) |
| 344 |
except CredentialsNotFound: |
| 345 |
# get raises an exception on not found. |
| 346 |
self.log(f"Credentials for {self.registry_url} not present, doing nothing.") |
| 347 |
self.results["changed"] = False |
| 348 |
return |
| 349 |
|
| 350 |
if not self.check_mode: |
| 351 |
store.erase(self.registry_url) |
| 352 |
self.results["changed"] = True |
| 353 |
|
| 354 |
def update_credentials(self) -> None: |
| 355 |
""" |
| 356 |
If the authorization is not stored attempt to store authorization values via |
| 357 |
the appropriate credential helper or to the config file. |
| 358 |
|
| 359 |
:return: None |
| 360 |
""" |
| 361 |
# This is only called from login() |
| 362 |
assert self.username is not None |
| 363 |
assert self.password is not None |
| 364 |
|
| 365 |
# Check to see if credentials already exist. |
| 366 |
store = self.get_credential_store_instance(self.registry_url, self.config_path) |
| 367 |
|
| 368 |
try: |
| 369 |
current = store.get(self.registry_url) |
| 370 |
except CredentialsNotFound: |
| 371 |
# get raises an exception on not found. |
| 372 |
current = {"Username": "", "Secret": ""} |
| 373 |
|
| 374 |
if ( |
| 375 |
current["Username"] != self.username |
| 376 |
or current["Secret"] != self.password |
| 377 |
or self.reauthorize |
| 378 |
): |
| 379 |
if not self.check_mode: |
| 380 |
store.store(self.registry_url, self.username, self.password) |
| 381 |
self.log( |
| 382 |
f"Writing credentials to configured helper {store.program} for {self.registry_url}" |
| 383 |
) |
| 384 |
self.results["actions"].append( |
| 385 |
f"Wrote credentials to configured helper {store.program} for {self.registry_url}" |
| 386 |
) |
| 387 |
self.results["changed"] = True |
| 388 |
|
| 389 |
def get_credential_store_instance( |
| 390 |
self, registry: str, dockercfg_path: str |
| 391 |
) -> Store | DockerFileStore: |
| 392 |
""" |
| 393 |
Return an instance of docker.credentials.Store used by the given registry. |
| 394 |
|
| 395 |
:return: A Store or None |
| 396 |
:rtype: Union[docker.credentials.Store, NoneType] |
| 397 |
""" |
| 398 |
|
| 399 |
credstore_env = self.client.credstore_env |
| 400 |
|
| 401 |
config = auth.load_config(config_path=dockercfg_path) |
| 402 |
|
| 403 |
store_name = auth.get_credential_store(config, registry) |
| 404 |
|
| 405 |
# Make sure that there is a credential helper before trying to instantiate a |
| 406 |
# Store object. |
| 407 |
if store_name: |
| 408 |
self.log(f"Found credential store {store_name}") |
| 409 |
return Store(store_name, environment=credstore_env) |
| 410 |
|
| 411 |
return DockerFileStore(dockercfg_path) |
| 412 |
|
| 413 |
|
| 414 |
def main() -> None: |
| 415 |
argument_spec = { |
| 416 |
"registry_url": { |
| 417 |
"type": "str", |
| 418 |
"default": DEFAULT_DOCKER_REGISTRY, |
| 419 |
"aliases": ["registry", "url"], |
| 420 |
}, |
| 421 |
"username": {"type": "str"}, |
| 422 |
"password": {"type": "str", "no_log": True}, |
| 423 |
"reauthorize": {"type": "bool", "default": False, "aliases": ["reauth"]}, |
| 424 |
"state": { |
| 425 |
"type": "str", |
| 426 |
"default": "present", |
| 427 |
"choices": ["present", "absent"], |
| 428 |
}, |
| 429 |
"config_path": { |
| 430 |
"type": "path", |
| 431 |
"default": "~/.docker/config.json", |
| 432 |
"aliases": ["dockercfg_path"], |
| 433 |
}, |
| 434 |
} |
| 435 |
|
| 436 |
required_if = [ |
| 437 |
("state", "present", ["username", "password"]), |
| 438 |
] |
| 439 |
|
| 440 |
client = AnsibleDockerClient( |
| 441 |
argument_spec=argument_spec, |
| 442 |
supports_check_mode=True, |
| 443 |
required_if=required_if, |
| 444 |
) |
| 445 |
|
| 446 |
try: |
| 447 |
results = {"changed": False, "actions": [], "login_result": {}} |
| 448 |
|
| 449 |
manager = LoginManager(client, results) |
| 450 |
manager.run() |
| 451 |
|
| 452 |
if "actions" in results: |
| 453 |
del results["actions"] |
| 454 |
client.module.exit_json(**results) |
| 455 |
except DockerException as e: |
| 456 |
client.fail( |
| 457 |
f"An unexpected Docker error occurred: {e}", |
| 458 |
exception=traceback.format_exc(), |
| 459 |
) |
| 460 |
except RequestException as e: |
| 461 |
client.fail( |
| 462 |
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}", |
| 463 |
exception=traceback.format_exc(), |
| 464 |
) |
| 465 |
|
| 466 |
|
| 467 |
if __name__ == "__main__": |
| 468 |
main() |