mirror of
https://github.com/ansible-collections/community.docker.git
synced 2026-07-29 11:55:04 +00:00
Python code modernization, 1/n (#1141)
* Remove unicode text prefixes. * Replace str.format() uses with f-strings. * Replace % with f-strings, and do some cleanup. * Fix wrong variable. * Avoid unnecessary string conversion.
This commit is contained in:
@@ -439,7 +439,6 @@ actions:
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.validation import check_type_int
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_cli import (
|
||||
AnsibleModuleDockerClient,
|
||||
@@ -477,17 +476,17 @@ class ServicesManager(BaseComposeManager):
|
||||
self.wait_timeout = parameters['wait_timeout']
|
||||
self.yes = parameters['assume_yes']
|
||||
if self.compose_version < LooseVersion('2.32.0') and self.yes:
|
||||
self.fail('assume_yes=true needs Docker Compose 2.32.0 or newer, not version %s' % (self.compose_version, ))
|
||||
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('The key %s for `scale` is not a string' % repr(key))
|
||||
self.fail(f'The key {key!r} for `scale` is not a string')
|
||||
try:
|
||||
value = check_type_int(value)
|
||||
except TypeError as exc:
|
||||
self.fail('The value %s for `scale[%s]` is not an integer' % (repr(value), repr(key)))
|
||||
self.fail(f'The value {value!r} for `scale[{key!r}]` is not an integer')
|
||||
if value < 0:
|
||||
self.fail('The value %s for `scale[%s]` is negative' % (repr(value), repr(key)))
|
||||
self.fail(f'The value {value!r} for `scale[{key!r}]` is negative')
|
||||
self.scale[key] = value
|
||||
|
||||
def run(self):
|
||||
@@ -520,13 +519,13 @@ class ServicesManager(BaseComposeManager):
|
||||
if not self.dependencies:
|
||||
args.append('--no-deps')
|
||||
if self.timeout is not None:
|
||||
args.extend(['--timeout', '%d' % self.timeout])
|
||||
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', '%s=%d' % (key, value)])
|
||||
args.extend(['--scale', f'{key}={value}'])
|
||||
if self.wait:
|
||||
args.append('--wait')
|
||||
if self.wait_timeout is not None:
|
||||
@@ -557,7 +556,7 @@ class ServicesManager(BaseComposeManager):
|
||||
def get_stop_cmd(self, dry_run):
|
||||
args = self.get_base_args() + ['stop']
|
||||
if self.timeout is not None:
|
||||
args.extend(['--timeout', '%d' % self.timeout])
|
||||
args.extend(['--timeout', f'{self.timeout}'])
|
||||
if dry_run:
|
||||
args.append('--dry-run')
|
||||
args.append('--')
|
||||
@@ -610,7 +609,7 @@ class ServicesManager(BaseComposeManager):
|
||||
if not self.dependencies:
|
||||
args.append('--no-deps')
|
||||
if self.timeout is not None:
|
||||
args.extend(['--timeout', '%d' % self.timeout])
|
||||
args.extend(['--timeout', f'{self.timeout}'])
|
||||
if dry_run:
|
||||
args.append('--dry-run')
|
||||
args.append('--')
|
||||
@@ -637,7 +636,7 @@ class ServicesManager(BaseComposeManager):
|
||||
if self.remove_volumes:
|
||||
args.append('--volumes')
|
||||
if self.timeout is not None:
|
||||
args.extend(['--timeout', '%d' % self.timeout])
|
||||
args.extend(['--timeout', f'{self.timeout}'])
|
||||
if dry_run:
|
||||
args.append('--dry-run')
|
||||
args.append('--')
|
||||
@@ -691,7 +690,7 @@ def main():
|
||||
manager.cleanup()
|
||||
client.module.exit_json(**result)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -167,7 +167,7 @@ rc:
|
||||
import shlex
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_text, to_native
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_cli import (
|
||||
AnsibleModuleDockerClient,
|
||||
@@ -211,7 +211,7 @@ class ExecManager(BaseComposeManager):
|
||||
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. Key: %s" % (name, )
|
||||
f"wrapped in quotes to avoid them being interpreted. Key: {name}"
|
||||
)
|
||||
self.env[name] = to_text(value, errors='surrogate_or_strict')
|
||||
|
||||
@@ -232,7 +232,7 @@ class ExecManager(BaseComposeManager):
|
||||
if self.env:
|
||||
for name, value in list(self.env.items()):
|
||||
args.append('--env')
|
||||
args.append('{0}={1}'.format(name, value))
|
||||
args.append(f'{name}={value}')
|
||||
args.append('--')
|
||||
args.append(self.service)
|
||||
args.extend(self.argv)
|
||||
@@ -295,7 +295,7 @@ def main():
|
||||
manager.cleanup()
|
||||
client.module.exit_json(**result)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -112,8 +112,6 @@ actions:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_cli import (
|
||||
AnsibleModuleDockerClient,
|
||||
DockerException,
|
||||
@@ -139,12 +137,12 @@ class PullManager(BaseComposeManager):
|
||||
|
||||
if self.policy != 'always' and self.compose_version < LooseVersion('2.22.0'):
|
||||
# https://github.com/docker/compose/pull/10981 - 2.22.0
|
||||
self.fail('A pull policy other than always is only supported since Docker Compose 2.22.0. {0} has version {1}'.format(
|
||||
self.client.get_cli(), self.compose_version))
|
||||
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('--ignore-buildable is only supported since Docker Compose 2.15.0. {0} has version {1}'.format(
|
||||
self.client.get_cli(), self.compose_version))
|
||||
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, no_start=False):
|
||||
args = self.get_base_args() + ['pull']
|
||||
@@ -196,7 +194,7 @@ def main():
|
||||
manager.cleanup()
|
||||
client.module.exit_json(**result)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -240,7 +240,7 @@ rc:
|
||||
import shlex
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_text, to_native
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_cli import (
|
||||
AnsibleModuleDockerClient,
|
||||
@@ -297,7 +297,7 @@ class ExecManager(BaseComposeManager):
|
||||
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. Key: %s" % (name, )
|
||||
f"wrapped in quotes to avoid them being interpreted. Key: {name}"
|
||||
)
|
||||
self.env[name] = to_text(value, errors='surrogate_or_strict')
|
||||
|
||||
@@ -349,7 +349,7 @@ class ExecManager(BaseComposeManager):
|
||||
if self.env:
|
||||
for name, value in list(self.env.items()):
|
||||
args.append('--env')
|
||||
args.append('{0}={1}'.format(name, value))
|
||||
args.append(f'{name}={value}')
|
||||
args.append('--')
|
||||
args.append(self.service)
|
||||
if self.argv:
|
||||
@@ -428,7 +428,7 @@ def main():
|
||||
manager.cleanup()
|
||||
client.module.exit_json(**result)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -214,7 +214,7 @@ from ansible_collections.community.docker.plugins.module_utils.util import (
|
||||
compare_generic,
|
||||
sanitize_labels,
|
||||
)
|
||||
from ansible.module_utils.common.text.converters import to_native, to_bytes
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
|
||||
|
||||
class ConfigManager(DockerBaseClass):
|
||||
@@ -242,7 +242,7 @@ class ConfigManager(DockerBaseClass):
|
||||
with open(data_src, 'rb') as f:
|
||||
self.data = f.read()
|
||||
except Exception as exc:
|
||||
self.client.fail('Error while reading {src}: {error}'.format(src=data_src, error=to_native(exc)))
|
||||
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')
|
||||
@@ -281,13 +281,13 @@ class ConfigManager(DockerBaseClass):
|
||||
try:
|
||||
configs = self.client.configs(filters={'name': self.name})
|
||||
except APIError as exc:
|
||||
self.client.fail("Error accessing config %s: %s" % (self.name, to_native(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('{name}_v'.format(name=self.name))
|
||||
if config['Spec']['Name'].startswith(f'{self.name}_v')
|
||||
]
|
||||
self.configs.sort(key=self.get_version)
|
||||
else:
|
||||
@@ -305,7 +305,7 @@ class ConfigManager(DockerBaseClass):
|
||||
if self.rolling_versions:
|
||||
self.version += 1
|
||||
labels['ansible_version'] = str(self.version)
|
||||
self.name = '{name}_v{version}'.format(name=self.name, version=self.version)
|
||||
self.name = f'{self.name}_v{self.version}'
|
||||
if self.labels:
|
||||
labels.update(self.labels)
|
||||
|
||||
@@ -320,7 +320,7 @@ class ConfigManager(DockerBaseClass):
|
||||
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("Error creating config: %s" % to_native(exc))
|
||||
self.client.fail(f"Error creating config: {exc}")
|
||||
|
||||
if isinstance(config_id, dict):
|
||||
config_id = config_id['ID']
|
||||
@@ -332,7 +332,7 @@ class ConfigManager(DockerBaseClass):
|
||||
if not self.check_mode:
|
||||
self.client.remove_config(config['ID'])
|
||||
except APIError as exc:
|
||||
self.client.fail("Error removing config %s: %s" % (config['Spec']['Name'], to_native(exc)))
|
||||
self.client.fail(f"Error removing config {config['Spec']['Name']}: {exc}")
|
||||
|
||||
def present(self):
|
||||
''' Handles state == 'present', creating or updating the config '''
|
||||
@@ -425,10 +425,10 @@ def main():
|
||||
ConfigManager(client, results)()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -451,7 +451,7 @@ def is_file_idempotent(client, container, managed_path, container_path, follow_l
|
||||
file_stat = os.stat(managed_path) if local_follow_links else os.lstat(managed_path)
|
||||
except OSError as exc:
|
||||
if exc.errno == 2:
|
||||
raise DockerFileNotFound('Cannot find local file {managed_path}'.format(managed_path=managed_path))
|
||||
raise DockerFileNotFound(f'Cannot find local file {managed_path}')
|
||||
raise
|
||||
if mode is None:
|
||||
mode = stat.S_IMODE(file_stat.st_mode)
|
||||
@@ -786,13 +786,13 @@ def parse_modern(mode):
|
||||
return int(to_native(mode), 8)
|
||||
if isinstance(mode, int):
|
||||
return mode
|
||||
raise TypeError('must be an octal string or an integer, got {mode!r}'.format(mode=mode))
|
||||
raise TypeError(f'must be an octal string or an integer, got {mode!r}')
|
||||
|
||||
|
||||
def parse_octal_string_only(mode):
|
||||
if isinstance(mode, str):
|
||||
return int(to_native(mode), 8)
|
||||
raise TypeError('must be an octal string, got {mode!r}'.format(mode=mode))
|
||||
raise TypeError(f'must be an octal string, got {mode!r}')
|
||||
|
||||
|
||||
def main():
|
||||
@@ -847,16 +847,16 @@ def main():
|
||||
elif mode_parse == 'octal_string_only':
|
||||
mode = parse_octal_string_only(mode)
|
||||
except (TypeError, ValueError) as e:
|
||||
client.fail("Error while parsing 'mode': {error}".format(error=e))
|
||||
client.fail(f"Error while parsing 'mode': {e}")
|
||||
if mode < 0:
|
||||
client.fail("'mode' must not be negative; got {mode}".format(mode=mode))
|
||||
client.fail(f"'mode' must not be negative; got {mode}")
|
||||
|
||||
if content is not None:
|
||||
if client.module.params['content_is_b64']:
|
||||
try:
|
||||
content = base64.b64decode(content)
|
||||
except Exception as e: # depending on Python version and error, multiple different exceptions can be raised
|
||||
client.fail('Cannot Base64 decode the content option: {0}'.format(e))
|
||||
client.fail(f'Cannot Base64 decode the content option: {e}')
|
||||
else:
|
||||
content = to_bytes(content)
|
||||
|
||||
@@ -901,21 +901,21 @@ def main():
|
||||
# Can happen if a user explicitly passes `content: null` or `path: null`...
|
||||
client.fail('One of path and content must be supplied')
|
||||
except NotFound as exc:
|
||||
client.fail('Could not find container "{1}" or resource in it ({0})'.format(exc, container))
|
||||
client.fail(f'Could not find container "{container}" or resource in it ({exc})')
|
||||
except APIError as exc:
|
||||
client.fail('An unexpected Docker error occurred for container "{1}": {0}'.format(exc, container), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred for container "{container}": {exc}', exception=traceback.format_exc())
|
||||
except DockerException as exc:
|
||||
client.fail('An unexpected Docker error occurred for container "{1}": {0}'.format(exc, container), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred for container "{container}": {exc}', exception=traceback.format_exc())
|
||||
except RequestException as exc:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred for container "{1}" when trying to talk to the Docker daemon: {0}'.format(exc, container),
|
||||
f'An unexpected requests error occurred for container "{container}" when trying to talk to the Docker daemon: {exc}',
|
||||
exception=traceback.format_exc())
|
||||
except DockerUnexpectedError as exc:
|
||||
client.fail('Unexpected error: {exc}'.format(exc=to_native(exc)), exception=traceback.format_exc())
|
||||
client.fail(f'Unexpected error: {exc}', exception=traceback.format_exc())
|
||||
except DockerFileCopyError as exc:
|
||||
client.fail(to_native(exc))
|
||||
except OSError as exc:
|
||||
client.fail('Unexpected error: {exc}'.format(exc=to_native(exc)), exception=traceback.format_exc())
|
||||
client.fail(f'Unexpected error: {exc}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -167,7 +167,7 @@ import selectors
|
||||
import shlex
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_text, to_bytes, to_native
|
||||
from ansible.module_utils.common.text.converters import to_text, to_bytes
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
@@ -228,7 +228,7 @@ def main():
|
||||
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. Key: %s" % (name, ))
|
||||
f"wrapped in quotes to avoid them being interpreted. Key: {name}")
|
||||
env[name] = to_text(value, errors='surrogate_or_strict')
|
||||
|
||||
if command is not None:
|
||||
@@ -295,16 +295,16 @@ def main():
|
||||
rc=result.get('ExitCode') or 0,
|
||||
)
|
||||
except NotFound:
|
||||
client.fail('Could not find container "{0}"'.format(container))
|
||||
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('The container "{0}" has been paused ({1})'.format(container, to_native(e)))
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
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('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -77,8 +77,6 @@ container:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -105,10 +103,10 @@ def main():
|
||||
container=container,
|
||||
)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ current_context_name:
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils.common.text.converters import to_native, to_text
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils._api.context.api import (
|
||||
ContextAPI,
|
||||
@@ -226,7 +226,7 @@ def context_to_json(context, current):
|
||||
if proto == 'http+unix':
|
||||
proto = 'unix'
|
||||
if proto:
|
||||
host_str = "{0}://{1}".format(proto, host_str)
|
||||
host_str = f"{proto}://{host_str}"
|
||||
|
||||
# Create config for the modules
|
||||
module_config['docker_host'] = host_str
|
||||
@@ -274,15 +274,12 @@ def main():
|
||||
if module.params['name']:
|
||||
contexts = [ContextAPI.get_context(module.params['name'])]
|
||||
if not contexts[0]:
|
||||
module.fail_json(msg="There is no context of name {name!r}".format(name=module.params['name']))
|
||||
module.fail_json(msg=f"There is no context of name {module.params['name']!r}")
|
||||
elif module.params['only_current']:
|
||||
contexts = [ContextAPI.get_context(current_context_name)]
|
||||
if not contexts[0]:
|
||||
module.fail_json(
|
||||
msg="There is no context of name {name!r}, which is configured as the default context ({source})".format(
|
||||
name=current_context_name,
|
||||
source=current_context_source,
|
||||
),
|
||||
msg=f"There is no context of name {current_context_name!r}, which is configured as the default context ({current_context_source})",
|
||||
)
|
||||
else:
|
||||
contexts = ContextAPI.contexts()
|
||||
@@ -298,9 +295,9 @@ def main():
|
||||
current_context_name=current_context_name,
|
||||
)
|
||||
except ContextException as e:
|
||||
module.fail_json(msg='Error when handling Docker contexts: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
module.fail_json(msg=f'Error when handling Docker contexts: {e}', exception=traceback.format_exc())
|
||||
except DockerException as e:
|
||||
module.fail_json(msg='An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
module.fail_json(msg=f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -213,8 +213,6 @@ disk_usage:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -259,7 +257,7 @@ class DockerHostManager(DockerBaseClass):
|
||||
try:
|
||||
return self.client.info()
|
||||
except APIError as exc:
|
||||
self.client.fail("Error inspecting docker host: %s" % to_native(exc))
|
||||
self.client.fail(f"Error inspecting docker host: {exc}")
|
||||
|
||||
def get_docker_disk_usage_facts(self):
|
||||
try:
|
||||
@@ -268,7 +266,7 @@ class DockerHostManager(DockerBaseClass):
|
||||
else:
|
||||
return dict(LayersSize=self.client.df()['LayersSize'])
|
||||
except APIError as exc:
|
||||
self.client.fail("Error inspecting docker host: %s" % to_native(exc))
|
||||
self.client.fail(f"Error inspecting docker host: {exc}")
|
||||
|
||||
def get_docker_items_list(self, docker_object=None, filters=None, verbose=False):
|
||||
items = None
|
||||
@@ -311,7 +309,7 @@ class DockerHostManager(DockerBaseClass):
|
||||
items = self.client.get_json('/volumes', params=params)
|
||||
items = items['Volumes']
|
||||
except APIError as exc:
|
||||
self.client.fail("Error inspecting docker host for object '%s': %s" % (docker_object, to_native(exc)))
|
||||
self.client.fail(f"Error inspecting docker host for object '{docker_object}': {exc}")
|
||||
|
||||
if self.verbose_output:
|
||||
return items
|
||||
@@ -370,10 +368,10 @@ def main():
|
||||
DockerHostManager(client, results)
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -417,7 +417,7 @@ def convert_to_bytes(value, module, name, unlimited_value=None):
|
||||
return unlimited_value
|
||||
return human_to_bytes(value)
|
||||
except ValueError as exc:
|
||||
module.fail_json(msg='Failed to convert %s to bytes: %s' % (name, to_native(exc)))
|
||||
module.fail_json(msg=f'Failed to convert {name} to bytes: {exc}')
|
||||
|
||||
|
||||
class ImageManager(DockerBaseClass):
|
||||
@@ -485,9 +485,9 @@ class ImageManager(DockerBaseClass):
|
||||
|
||||
# Sanity check: fail early when we know that something will fail later
|
||||
if self.repository and is_image_name_id(self.repository):
|
||||
self.fail("`repository` must not be an image ID; got: %s" % self.repository)
|
||||
self.fail(f"`repository` must not be an image ID; got: {self.repository}")
|
||||
if not self.repository and self.push and is_image_name_id(self.name):
|
||||
self.fail("Cannot push an image by ID; specify `repository` to tag and push the image with ID %s instead" % self.name)
|
||||
self.fail(f"Cannot push an image by ID; specify `repository` to tag and push the image with ID {self.name} instead")
|
||||
|
||||
if self.state == 'present':
|
||||
self.present()
|
||||
@@ -512,16 +512,16 @@ class ImageManager(DockerBaseClass):
|
||||
if not image or self.force_source:
|
||||
if self.source == 'build':
|
||||
if is_image_name_id(self.name):
|
||||
self.fail("Image name must not be an image ID for source=build; got: %s" % self.name)
|
||||
self.fail(f"Image name must not be an image ID for source=build; got: {self.name}")
|
||||
|
||||
# Build the image
|
||||
if not os.path.isdir(self.build_path):
|
||||
self.fail("Requested build path %s could not be found or you do not have access." % self.build_path)
|
||||
self.fail(f"Requested build path {self.build_path} could not be found or you do not have access.")
|
||||
image_name = self.name
|
||||
if self.tag:
|
||||
image_name = "%s:%s" % (self.name, self.tag)
|
||||
self.log("Building image %s" % image_name)
|
||||
self.results['actions'].append("Built image %s from %s" % (image_name, self.build_path))
|
||||
image_name = f"{self.name}:{self.tag}"
|
||||
self.log(f"Building image {image_name}")
|
||||
self.results['actions'].append(f"Built image {image_name} from {self.build_path}")
|
||||
self.results['changed'] = True
|
||||
if not self.check_mode:
|
||||
self.results.update(self.build_image())
|
||||
@@ -529,21 +529,20 @@ class ImageManager(DockerBaseClass):
|
||||
elif self.source == 'load':
|
||||
# Load the image from an archive
|
||||
if not os.path.isfile(self.load_path):
|
||||
self.fail("Error loading image %s. Specified path %s does not exist." % (self.name,
|
||||
self.load_path))
|
||||
self.fail(f"Error loading image {self.name}. Specified path {self.load_path} does not exist.")
|
||||
image_name = self.name
|
||||
if self.tag and not is_image_name_id(image_name):
|
||||
image_name = "%s:%s" % (self.name, self.tag)
|
||||
self.results['actions'].append("Loaded image %s from %s" % (image_name, self.load_path))
|
||||
image_name = f"{self.name}:{self.tag}"
|
||||
self.results['actions'].append(f"Loaded image {image_name} from {self.load_path}")
|
||||
self.results['changed'] = True
|
||||
if not self.check_mode:
|
||||
self.results['image'] = self.load_image()
|
||||
elif self.source == 'pull':
|
||||
if is_image_name_id(self.name):
|
||||
self.fail("Image name must not be an image ID for source=pull; got: %s" % self.name)
|
||||
self.fail(f"Image name must not be an image ID for source=pull; got: {self.name}")
|
||||
|
||||
# pull the image
|
||||
self.results['actions'].append('Pulled image %s:%s' % (self.name, self.tag))
|
||||
self.results['actions'].append(f'Pulled image {self.name}:{self.tag}')
|
||||
self.results['changed'] = True
|
||||
if not self.check_mode:
|
||||
self.results['image'], dummy = self.client.pull_image(self.name, tag=self.tag, platform=self.pull_platform)
|
||||
@@ -551,8 +550,8 @@ class ImageManager(DockerBaseClass):
|
||||
if image is None:
|
||||
name = self.name
|
||||
if self.tag and not is_image_name_id(name):
|
||||
name = "%s:%s" % (self.name, self.tag)
|
||||
self.client.fail('Cannot find the image %s locally.' % name)
|
||||
name = f"{self.name}:{self.tag}"
|
||||
self.client.fail(f'Cannot find the image {name} locally.')
|
||||
if not self.check_mode and image and image['Id'] == self.results['image']['Id']:
|
||||
self.results['changed'] = False
|
||||
else:
|
||||
@@ -578,7 +577,7 @@ class ImageManager(DockerBaseClass):
|
||||
else:
|
||||
image = self.client.find_image(name, self.tag)
|
||||
if self.tag:
|
||||
name = "%s:%s" % (self.name, self.tag)
|
||||
name = f"{self.name}:{self.tag}"
|
||||
if image:
|
||||
if not self.check_mode:
|
||||
try:
|
||||
@@ -587,10 +586,10 @@ class ImageManager(DockerBaseClass):
|
||||
# If the image vanished while we were trying to remove it, do not fail
|
||||
pass
|
||||
except Exception as exc:
|
||||
self.fail("Error removing image %s - %s" % (name, to_native(exc)))
|
||||
self.fail(f"Error removing image {name} - {exc}")
|
||||
|
||||
self.results['changed'] = True
|
||||
self.results['actions'].append("Removed image %s" % (name))
|
||||
self.results['actions'].append(f"Removed image {name}")
|
||||
self.results['image']['state'] = 'Deleted'
|
||||
|
||||
@staticmethod
|
||||
@@ -612,12 +611,12 @@ class ImageManager(DockerBaseClass):
|
||||
'''
|
||||
|
||||
def build_msg(reason):
|
||||
return 'Archived image %s to %s, %s' % (current_image_name, archive_path, reason)
|
||||
return f'Archived image {current_image_name} to {archive_path}, {reason}'
|
||||
|
||||
try:
|
||||
archived = archived_image_manifest(archive_path)
|
||||
except ImageArchiveInvalidException as exc:
|
||||
failure_logger('Unable to extract manifest summary from archive: %s' % to_native(exc))
|
||||
failure_logger(f'Unable to extract manifest summary from archive: {exc}')
|
||||
return build_msg('overwriting an unreadable archive file')
|
||||
|
||||
if archived is None:
|
||||
@@ -627,7 +626,7 @@ class ImageManager(DockerBaseClass):
|
||||
else:
|
||||
name = ', '.join(archived.repo_tags)
|
||||
|
||||
return build_msg('overwriting archive with image %s named %s' % (archived.image_id, name))
|
||||
return build_msg(f'overwriting archive with image {archived.image_id} named {name}')
|
||||
|
||||
def archive_image(self, name, tag):
|
||||
'''
|
||||
@@ -647,10 +646,10 @@ class ImageManager(DockerBaseClass):
|
||||
image_name = name
|
||||
else:
|
||||
image = self.client.find_image(name=name, tag=tag)
|
||||
image_name = "%s:%s" % (name, tag)
|
||||
image_name = f"{name}:{tag}"
|
||||
|
||||
if not image:
|
||||
self.log("archive image: image %s not found" % image_name)
|
||||
self.log(f"archive image: image {image_name} not found")
|
||||
return
|
||||
|
||||
# Will have a 'sha256:' prefix
|
||||
@@ -664,7 +663,7 @@ class ImageManager(DockerBaseClass):
|
||||
self.results['changed'] = action is not None
|
||||
|
||||
if (not self.check_mode) and self.results['changed']:
|
||||
self.log("Getting archive of image %s" % image_name)
|
||||
self.log(f"Getting archive of image {image_name}")
|
||||
try:
|
||||
saved_image = self.client._stream_raw_result(
|
||||
self.client._get(self.client._url('/images/{0}/get', image_name), stream=True),
|
||||
@@ -672,14 +671,14 @@ class ImageManager(DockerBaseClass):
|
||||
False,
|
||||
)
|
||||
except Exception as exc:
|
||||
self.fail("Error getting image %s - %s" % (image_name, to_native(exc)))
|
||||
self.fail(f"Error getting image {image_name} - {exc}")
|
||||
|
||||
try:
|
||||
with open(self.archive_path, 'wb') as fd:
|
||||
for chunk in saved_image:
|
||||
fd.write(chunk)
|
||||
except Exception as exc:
|
||||
self.fail("Error writing image archive %s - %s" % (self.archive_path, to_native(exc)))
|
||||
self.fail(f"Error writing image archive {self.archive_path} - {exc}")
|
||||
|
||||
self.results['image'] = image
|
||||
|
||||
@@ -693,17 +692,17 @@ class ImageManager(DockerBaseClass):
|
||||
'''
|
||||
|
||||
if is_image_name_id(name):
|
||||
self.fail("Cannot push an image ID: %s" % name)
|
||||
self.fail(f"Cannot push an image ID: {name}")
|
||||
|
||||
repository = name
|
||||
if not tag:
|
||||
repository, tag = parse_repository_tag(name)
|
||||
registry, repo_name = resolve_repository_name(repository)
|
||||
|
||||
self.log("push %s to %s/%s:%s" % (self.name, registry, repo_name, tag))
|
||||
self.log(f"push {self.name} to {registry}/{repo_name}:{tag}")
|
||||
|
||||
if registry:
|
||||
self.results['actions'].append("Pushed image %s to %s/%s:%s" % (self.name, registry, repo_name, tag))
|
||||
self.results['actions'].append(f"Pushed image {self.name} to {registry}/{repo_name}:{tag}")
|
||||
self.results['changed'] = True
|
||||
if not self.check_mode:
|
||||
status = None
|
||||
@@ -740,12 +739,10 @@ class ImageManager(DockerBaseClass):
|
||||
except Exception as exc:
|
||||
if 'unauthorized' in str(exc):
|
||||
if 'authentication required' in str(exc):
|
||||
self.fail("Error pushing image %s/%s:%s - %s. Try logging into %s first." %
|
||||
(registry, repo_name, tag, to_native(exc), registry))
|
||||
self.fail(f"Error pushing image {registry}/{repo_name}:{tag} - {exc}. Try logging into {registry} first.")
|
||||
else:
|
||||
self.fail("Error pushing image %s/%s:%s - %s. Does the repository exist?" %
|
||||
(registry, repo_name, tag, str(exc)))
|
||||
self.fail("Error pushing image %s: %s" % (repository, to_native(exc)))
|
||||
self.fail(f"Error pushing image {registry}/{repo_name}:{tag} - {exc}. Does the repository exist?")
|
||||
self.fail(f"Error pushing image {repository}: {exc}")
|
||||
self.results['image'] = self.client.find_image(name=repository, tag=tag)
|
||||
if not self.results['image']:
|
||||
self.results['image'] = dict()
|
||||
@@ -768,15 +765,15 @@ class ImageManager(DockerBaseClass):
|
||||
repo_tag = tag
|
||||
image = self.client.find_image(name=repo, tag=repo_tag)
|
||||
found = 'found' if image else 'not found'
|
||||
self.log("image %s was %s" % (repo, found))
|
||||
self.log(f"image {repo} was {found}")
|
||||
|
||||
if not image or self.force_tag:
|
||||
image_name = name
|
||||
if not is_image_name_id(name) and tag and not name.endswith(':' + tag):
|
||||
image_name = "%s:%s" % (name, tag)
|
||||
self.log("tagging %s to %s:%s" % (image_name, repo, repo_tag))
|
||||
image_name = f"{name}:{tag}"
|
||||
self.log(f"tagging {image_name} to {repo}:{repo_tag}")
|
||||
self.results['changed'] = True
|
||||
self.results['actions'].append("Tagged image %s to %s:%s" % (image_name, repo, repo_tag))
|
||||
self.results['actions'].append(f"Tagged image {image_name} to {repo}:{repo_tag}")
|
||||
if not self.check_mode:
|
||||
try:
|
||||
# Finding the image does not always work, especially running a localhost registry. In those
|
||||
@@ -791,7 +788,7 @@ class ImageManager(DockerBaseClass):
|
||||
if res.status_code != 201:
|
||||
raise Exception("Tag operation failed.")
|
||||
except Exception as exc:
|
||||
self.fail("Error: failed to tag image - %s" % to_native(exc))
|
||||
self.fail(f"Error: failed to tag image - {exc}")
|
||||
self.results['image'] = self.client.find_image(name=repo, tag=repo_tag)
|
||||
if image and image['Id'] == self.results['image']['Id']:
|
||||
self.results['changed'] = False
|
||||
@@ -826,7 +823,7 @@ class ImageManager(DockerBaseClass):
|
||||
container_limits = self.container_limits or {}
|
||||
for key in container_limits.keys():
|
||||
if key not in CONTAINER_LIMITS_KEYS:
|
||||
raise DockerException('Invalid container_limits key {key}'.format(key=key))
|
||||
raise DockerException(f'Invalid container_limits key {key}')
|
||||
|
||||
dockerfile = self.dockerfile
|
||||
if self.build_path.startswith(('http://', 'https://', 'git://', 'github.com/', 'git@')):
|
||||
@@ -846,7 +843,7 @@ class ImageManager(DockerBaseClass):
|
||||
context = tar(self.build_path, exclude=exclude, dockerfile=dockerfile, gzip=False)
|
||||
|
||||
params = {
|
||||
't': "%s:%s" % (self.name, self.tag) if self.tag else self.name,
|
||||
't': f"{self.name}:{self.tag}" if self.tag else self.name,
|
||||
'remote': remote,
|
||||
'q': False,
|
||||
'nocache': self.nocache,
|
||||
@@ -912,14 +909,9 @@ class ImageManager(DockerBaseClass):
|
||||
if line.get('errorDetail'):
|
||||
errorDetail = line.get('errorDetail')
|
||||
self.fail(
|
||||
"Error building %s - code: %s, message: %s, logs: %s" % (
|
||||
self.name,
|
||||
errorDetail.get('code'),
|
||||
errorDetail.get('message'),
|
||||
build_output))
|
||||
f"Error building {self.name} - code: {errorDetail.get('code')}, message: {errorDetail.get('message')}, logs: {build_output}")
|
||||
else:
|
||||
self.fail("Error building %s - message: %s, logs: %s" % (
|
||||
self.name, line.get('error'), build_output))
|
||||
self.fail(f"Error building {self.name} - message: {line.get('error')}, logs: {build_output}")
|
||||
|
||||
return {
|
||||
"stdout": "\n".join(build_output),
|
||||
@@ -936,9 +928,9 @@ class ImageManager(DockerBaseClass):
|
||||
load_output = []
|
||||
has_output = False
|
||||
try:
|
||||
self.log("Opening image %s" % self.load_path)
|
||||
self.log(f"Opening image {self.load_path}")
|
||||
with open(self.load_path, 'rb') as image_tar:
|
||||
self.log("Loading image from %s" % self.load_path)
|
||||
self.log(f"Loading image from {self.load_path}")
|
||||
res = self.client._post(self.client._url("/images/load"), data=image_tar, stream=True)
|
||||
if LooseVersion(self.client.api_version) >= LooseVersion('1.23'):
|
||||
has_output = True
|
||||
@@ -955,10 +947,10 @@ class ImageManager(DockerBaseClass):
|
||||
)
|
||||
except EnvironmentError as exc:
|
||||
if exc.errno == errno.ENOENT:
|
||||
self.client.fail("Error opening image %s - %s" % (self.load_path, to_native(exc)))
|
||||
self.client.fail("Error loading image %s - %s" % (self.name, to_native(exc)), stdout='\n'.join(load_output))
|
||||
self.client.fail(f"Error opening image {self.load_path} - {exc}")
|
||||
self.client.fail(f"Error loading image {self.name} - {exc}", stdout='\n'.join(load_output))
|
||||
except Exception as exc:
|
||||
self.client.fail("Error loading image %s - %s" % (self.name, to_native(exc)), stdout='\n'.join(load_output))
|
||||
self.client.fail(f"Error loading image {self.name} - {exc}", stdout='\n'.join(load_output))
|
||||
|
||||
# Collect loaded images
|
||||
if has_output:
|
||||
@@ -978,20 +970,19 @@ class ImageManager(DockerBaseClass):
|
||||
expected_image = self.name.lower()
|
||||
found_image = expected_image not in loaded_image_ids
|
||||
else:
|
||||
expected_image = '%s:%s' % (self.name, self.tag)
|
||||
expected_image = f'{self.name}:{self.tag}'
|
||||
found_image = expected_image not in loaded_images
|
||||
if found_image:
|
||||
found_instead = ', '.join(sorted([f"'{image}'" for image in loaded_images] + list(loaded_image_ids)))
|
||||
self.client.fail(
|
||||
"The archive did not contain image '%s'. Instead, found %s." % (
|
||||
expected_image,
|
||||
', '.join(sorted(["'%s'" % image for image in loaded_images] + list(loaded_image_ids)))),
|
||||
f"The archive did not contain image '{expected_image}'. Instead, found {found_instead}.",
|
||||
stdout='\n'.join(load_output))
|
||||
loaded_images.remove(expected_image)
|
||||
|
||||
if loaded_images:
|
||||
found_more = ', '.join(sorted([f"'{image}'" for image in loaded_images] + list(loaded_image_ids)))
|
||||
self.client.module.warn(
|
||||
"The archive contained more images than specified: %s" % (
|
||||
', '.join(sorted(["'%s'" % image for image in loaded_images] + list(loaded_image_ids))), ))
|
||||
f"The archive contained more images than specified: {found_more}")
|
||||
|
||||
if is_image_name_id(self.name):
|
||||
return self.client.find_image_by_id(self.name, accept_missing_image=True)
|
||||
@@ -1068,7 +1059,7 @@ def main():
|
||||
)
|
||||
|
||||
if not is_valid_tag(client.module.params['tag'], allow_empty=True):
|
||||
client.fail('"{0}" is not a valid docker tag!'.format(client.module.params['tag']))
|
||||
client.fail(f'"{client.module.params["tag"]}" is not a valid docker tag!')
|
||||
|
||||
if client.module.params['source'] == 'build':
|
||||
if not client.module.params['build'] or not client.module.params['build'].get('path'):
|
||||
@@ -1084,10 +1075,10 @@ def main():
|
||||
ImageManager(client, results)
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -313,17 +313,18 @@ def convert_to_bytes(value, module, name, unlimited_value=None):
|
||||
return unlimited_value
|
||||
return human_to_bytes(value)
|
||||
except ValueError as exc:
|
||||
module.fail_json(msg='Failed to convert %s to bytes: %s' % (name, to_native(exc)))
|
||||
module.fail_json(msg=f'Failed to convert {name} to bytes: {exc}')
|
||||
|
||||
|
||||
def dict_to_list(dictionary, concat='='):
|
||||
return ['%s%s%s' % (k, concat, v) for k, v in sorted(dictionary.items())]
|
||||
return [f'{k}{concat}{v}' for k, v in sorted(dictionary.items())]
|
||||
|
||||
|
||||
def _quote_csv(input):
|
||||
if input.strip() == input and all(i not in input for i in '",\r\n'):
|
||||
return input
|
||||
return '"{0}"'.format(input.replace('"', '""'))
|
||||
input = input.replace('"', '""')
|
||||
return f'"{input}"'
|
||||
|
||||
|
||||
class ImageBuilder(DockerBaseClass):
|
||||
@@ -349,33 +350,29 @@ class ImageBuilder(DockerBaseClass):
|
||||
|
||||
buildx = self.client.get_client_plugin_info('buildx')
|
||||
if buildx is None:
|
||||
self.fail('Docker CLI {0} does not have the buildx plugin installed'.format(self.client.get_cli()))
|
||||
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'):
|
||||
if LooseVersion(buildx_version) < LooseVersion('0.6.0'):
|
||||
self.fail('The Docker buildx plugin has version {version}, but 0.6.0 is needed for secrets of type=env and type=value'.format(
|
||||
version=buildx_version,
|
||||
))
|
||||
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:
|
||||
if LooseVersion(buildx_version) < LooseVersion('0.13.0'):
|
||||
self.fail('The Docker buildx plugin has version {version}, but 0.13.0 is needed to specify more than one output'.format(
|
||||
version=buildx_version,
|
||||
))
|
||||
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('"{0}" is not an existing directory'.format(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('"{0}" is not an existing file'.format(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('"{0}" is not a valid docker tag'.format(self.tag))
|
||||
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')
|
||||
|
||||
@@ -390,7 +387,7 @@ class ImageBuilder(DockerBaseClass):
|
||||
|
||||
if self.outputs:
|
||||
found = False
|
||||
name_tag = '%s:%s' % (self.name, self.tag)
|
||||
name_tag = f'{self.name}:{self.tag}'
|
||||
for output in self.outputs:
|
||||
if output['type'] == 'image':
|
||||
if not output['name']:
|
||||
@@ -406,11 +403,8 @@ class ImageBuilder(DockerBaseClass):
|
||||
})
|
||||
if LooseVersion(buildx_version) < LooseVersion('0.13.0'):
|
||||
self.fail(
|
||||
"The output does not include an image with name {name_tag}, and the Docker"
|
||||
" buildx plugin has version {version} which only supports one output.".format(
|
||||
name_tag=name_tag,
|
||||
version=buildx_version,
|
||||
),
|
||||
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, **kwargs):
|
||||
@@ -423,7 +417,7 @@ class ImageBuilder(DockerBaseClass):
|
||||
def add_args(self, args):
|
||||
environ_update = {}
|
||||
if not self.outputs:
|
||||
args.extend(['--tag', '%s:%s' % (self.name, self.tag)])
|
||||
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:
|
||||
@@ -450,41 +444,47 @@ class ImageBuilder(DockerBaseClass):
|
||||
if self.secrets:
|
||||
random_prefix = None
|
||||
for index, secret in enumerate(self.secrets):
|
||||
sid = secret['id']
|
||||
if secret['type'] == 'file':
|
||||
args.extend(['--secret', 'id={id},type=file,src={src}'.format(id=secret['id'], src=secret['src'])])
|
||||
src = secret['src']
|
||||
args.extend(['--secret', f'id={sid},type=file,src={src}'])
|
||||
if secret['type'] == 'env':
|
||||
args.extend(['--secret', 'id={id},type=env,env={env}'.format(id=secret['id'], env=secret['src'])])
|
||||
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 = 'ANSIBLE_DOCKER_COMPOSE_ENV_SECRET_{random}_{id}'.format(
|
||||
random=random_prefix,
|
||||
id=index,
|
||||
)
|
||||
env_name = f'ANSIBLE_DOCKER_COMPOSE_ENV_SECRET_{random_prefix}_{index}'
|
||||
environ_update[env_name] = secret['value']
|
||||
args.extend(['--secret', 'id={id},type=env,env={env}'.format(id=secret['id'], env=env_name)])
|
||||
args.extend(['--secret', f'id={sid},type=env,env={env_name}'])
|
||||
if self.outputs:
|
||||
for output in self.outputs:
|
||||
subargs = []
|
||||
if output['type'] == 'local':
|
||||
subargs.extend(['type=local', 'dest={dest}'.format(dest=output['dest'])])
|
||||
dest = output['dest']
|
||||
subargs.extend(['type=local', f'dest={dest}'])
|
||||
if output['type'] == 'tar':
|
||||
subargs.extend(['type=tar', 'dest={dest}'.format(dest=output['dest'])])
|
||||
dest = output['dest']
|
||||
subargs.extend(['type=tar', f'dest={dest}'])
|
||||
if output['type'] == 'oci':
|
||||
subargs.extend(['type=oci', 'dest={dest}'.format(dest=output['dest'])])
|
||||
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('dest={dest}'.format(dest=output['dest']))
|
||||
subargs.append(f'dest={dest}')
|
||||
if output['context'] is not None:
|
||||
subargs.append('context={context}'.format(context=output['context']))
|
||||
context = output['context']
|
||||
subargs.append(f'context={context}')
|
||||
if output['type'] == 'image':
|
||||
subargs.append('type=image')
|
||||
if output['name'] is not None:
|
||||
subargs.append('name={name}'.format(name=','.join(output['name'])))
|
||||
name = ','.join(output['name'])
|
||||
subargs.append(f'name={name}')
|
||||
if output['push']:
|
||||
subargs.append('push=true')
|
||||
if subargs:
|
||||
@@ -510,7 +510,7 @@ class ImageBuilder(DockerBaseClass):
|
||||
args.extend(['--', self.path])
|
||||
rc, stdout, stderr = self.client.call_cli(*args, environ_update=environ_update)
|
||||
if rc != 0:
|
||||
self.fail('Building %s:%s failed' % (self.name, self.tag), stdout=to_native(stdout), stderr=to_native(stderr), command=args)
|
||||
self.fail(f'Building {self.name}:{self.tag} failed', stdout=to_native(stdout), stderr=to_native(stderr), command=args)
|
||||
results['stdout'] = to_native(stdout)
|
||||
results['stderr'] = to_native(stderr)
|
||||
results['image'] = self.client.find_image(self.name, self.tag) or {}
|
||||
@@ -590,7 +590,7 @@ def main():
|
||||
results = ImageBuilder(client).build_image()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -95,8 +95,6 @@ images:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -135,7 +133,7 @@ class ImageExportManager(DockerBaseClass):
|
||||
self.tag = parameters['tag']
|
||||
|
||||
if not is_valid_tag(self.tag, allow_empty=True):
|
||||
self.fail('"{0}" is not a valid docker tag'.format(self.tag))
|
||||
self.fail(f'"{self.tag}" is not a valid docker tag')
|
||||
|
||||
# If name contains a tag, it takes precedence over tag parameter.
|
||||
self.names = []
|
||||
@@ -146,7 +144,7 @@ class ImageExportManager(DockerBaseClass):
|
||||
repo, repo_tag = parse_repository_tag(name)
|
||||
if not repo_tag:
|
||||
repo_tag = self.tag
|
||||
self.names.append({'name': repo, 'tag': repo_tag, 'joined': '%s:%s' % (repo, repo_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')
|
||||
@@ -163,7 +161,7 @@ class ImageExportManager(DockerBaseClass):
|
||||
if archived_images is None:
|
||||
return 'Overwriting since no image is present in archive'
|
||||
except ImageArchiveInvalidException as exc:
|
||||
self.log('Unable to extract manifest summary from archive: %s' % to_native(exc))
|
||||
self.log(f'Unable to extract manifest summary from archive: {exc}')
|
||||
return 'Overwriting an unreadable archive file'
|
||||
|
||||
left_names = list(self.names)
|
||||
@@ -175,11 +173,9 @@ class ImageExportManager(DockerBaseClass):
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
return 'Overwriting archive since it contains unexpected image %s named %s' % (
|
||||
archived_image.image_id, ', '.join(archived_image.repo_tags)
|
||||
)
|
||||
return f'Overwriting archive since it contains unexpected image {archived_image.image_id} named {", ".join(archived_image.repo_tags)}'
|
||||
if left_names:
|
||||
return 'Overwriting archive since it is missing image(s) %s' % (', '.join([name['joined'] for name in left_names]))
|
||||
return f"Overwriting archive since it is missing image(s) {', '.join([name['joined'] for name in left_names])}"
|
||||
|
||||
return None
|
||||
|
||||
@@ -189,13 +185,13 @@ class ImageExportManager(DockerBaseClass):
|
||||
for chunk in chunks:
|
||||
fd.write(chunk)
|
||||
except Exception as exc:
|
||||
self.fail("Error writing image archive %s - %s" % (self.path, to_native(exc)))
|
||||
self.fail(f"Error writing image archive {self.path} - {exc}")
|
||||
|
||||
def export_images(self):
|
||||
image_names = [name['joined'] for name in self.names]
|
||||
image_names_str = ', '.join(image_names)
|
||||
if len(image_names) == 1:
|
||||
self.log("Getting archive of image %s" % image_names[0])
|
||||
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),
|
||||
@@ -203,9 +199,9 @@ class ImageExportManager(DockerBaseClass):
|
||||
False,
|
||||
)
|
||||
except Exception as exc:
|
||||
self.fail("Error getting image %s - %s" % (image_names[0], to_native(exc)))
|
||||
self.fail(f"Error getting image {image_names[0]} - {exc}")
|
||||
else:
|
||||
self.log("Getting archive of images %s" % image_names_str)
|
||||
self.log(f"Getting archive of images {image_names_str}")
|
||||
try:
|
||||
chunks = self.client._stream_raw_result(
|
||||
self.client._get(
|
||||
@@ -217,7 +213,7 @@ class ImageExportManager(DockerBaseClass):
|
||||
False,
|
||||
)
|
||||
except Exception as exc:
|
||||
self.fail("Error getting images %s - %s" % (image_names_str, to_native(exc)))
|
||||
self.fail(f"Error getting images {image_names_str} - {exc}")
|
||||
|
||||
self.write_chunks(chunks)
|
||||
|
||||
@@ -233,7 +229,7 @@ class ImageExportManager(DockerBaseClass):
|
||||
else:
|
||||
image = self.client.find_image(name=name['name'], tag=name['tag'])
|
||||
if not image:
|
||||
self.fail("Image %s not found" % name['joined'])
|
||||
self.fail(f"Image {name['joined']} not found")
|
||||
images.append(image)
|
||||
|
||||
# Will have a 'sha256:' prefix
|
||||
@@ -272,10 +268,10 @@ def main():
|
||||
results = ImageExportManager(client).run()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -137,8 +137,6 @@ images:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -160,7 +158,7 @@ class ImageManager(DockerBaseClass):
|
||||
self.client = client
|
||||
self.results = results
|
||||
self.name = self.client.module.params.get('name')
|
||||
self.log("Gathering facts for images: %s" % (str(self.name)))
|
||||
self.log(f"Gathering facts for images: {self.name}")
|
||||
|
||||
if self.name:
|
||||
self.results['images'] = self.get_facts()
|
||||
@@ -185,13 +183,13 @@ class ImageManager(DockerBaseClass):
|
||||
|
||||
for name in names:
|
||||
if is_image_name_id(name):
|
||||
self.log('Fetching image %s (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('Fetching image %s:%s' % (repository, tag))
|
||||
self.log(f'Fetching image {repository}:{tag}')
|
||||
image = self.client.find_image(name=repository, tag=tag)
|
||||
if image:
|
||||
results.append(image)
|
||||
@@ -210,7 +208,7 @@ class ImageManager(DockerBaseClass):
|
||||
except NotFound:
|
||||
inspection = None
|
||||
except Exception as exc:
|
||||
self.fail("Error inspecting image %s - %s" % (image['Id'], to_native(exc)))
|
||||
self.fail(f"Error inspecting image {image['Id']} - {exc}")
|
||||
results.append(inspection)
|
||||
return results
|
||||
|
||||
@@ -234,10 +232,10 @@ def main():
|
||||
ImageManager(client, results)
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -82,8 +82,6 @@ images:
|
||||
import errno
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -127,19 +125,19 @@ class ImageManager(DockerBaseClass):
|
||||
# Load image(s) from file
|
||||
load_output = []
|
||||
try:
|
||||
self.log("Opening image {0}".format(self.path))
|
||||
self.log(f"Opening image {self.path}")
|
||||
with open(self.path, 'rb') as image_tar:
|
||||
self.log("Loading images from {0}".format(self.path))
|
||||
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("Error opening archive {0} - {1}".format(self.path, to_native(exc)))
|
||||
self.client.fail("Error loading archive {0} - {1}".format(self.path, to_native(exc)), stdout='\n'.join(load_output))
|
||||
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:
|
||||
self.client.fail("Error loading archive {0} - {1}".format(self.path, to_native(exc)), stdout='\n'.join(load_output))
|
||||
self.client.fail(f"Error loading archive {self.path} - {exc}", stdout='\n'.join(load_output))
|
||||
|
||||
# Collect loaded images
|
||||
loaded_images = []
|
||||
@@ -160,7 +158,7 @@ class ImageManager(DockerBaseClass):
|
||||
image_name, tag = image_name.rsplit(':', 1)
|
||||
images.append(self.client.find_image(image_name, tag))
|
||||
else:
|
||||
self.client.module.warn('Image name "{0}" is neither ID nor has a tag'.format(image_name))
|
||||
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
|
||||
@@ -185,10 +183,10 @@ def main():
|
||||
ImageManager(client, results)
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -92,8 +92,6 @@ image:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -142,7 +140,7 @@ class ImagePuller(DockerBaseClass):
|
||||
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('"{0}" is not a valid docker tag!'.format(self.tag))
|
||||
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)
|
||||
@@ -178,7 +176,7 @@ class ImagePuller(DockerBaseClass):
|
||||
if compare_platform_strings(wanted_platform, image_platform):
|
||||
return results
|
||||
|
||||
results['actions'].append('Pulled image %s:%s' % (self.name, self.tag))
|
||||
results['actions'].append(f'Pulled image {self.name}:{self.tag}')
|
||||
if self.check_mode:
|
||||
results['changed'] = True
|
||||
results['diff']['after'] = image_info(dict(Id='unknown'))
|
||||
@@ -212,10 +210,10 @@ def main():
|
||||
results = ImagePuller(client).pull()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -74,8 +74,6 @@ image:
|
||||
import base64
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -112,7 +110,7 @@ class ImagePusher(DockerBaseClass):
|
||||
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('"{0}" is not a valid docker tag!'.format(self.tag))
|
||||
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)
|
||||
@@ -123,12 +121,12 @@ class ImagePusher(DockerBaseClass):
|
||||
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('"{0}" is not a valid docker tag!'.format(self.tag))
|
||||
self.client.fail(f'"{self.tag}" is not a valid docker tag!')
|
||||
|
||||
def push(self):
|
||||
image = self.client.find_image(name=self.name, tag=self.tag)
|
||||
if not image:
|
||||
self.client.fail('Cannot find image %s:%s' % (self.name, self.tag))
|
||||
self.client.fail(f'Cannot find image {self.name}:{self.tag}')
|
||||
|
||||
results = dict(
|
||||
changed=False,
|
||||
@@ -138,7 +136,7 @@ class ImagePusher(DockerBaseClass):
|
||||
|
||||
push_registry, push_repo = resolve_repository_name(self.name)
|
||||
try:
|
||||
results['actions'].append('Pushed image %s:%s' % (self.name, self.tag))
|
||||
results['actions'].append(f'Pushed image {self.name}:{self.tag}')
|
||||
|
||||
headers = {}
|
||||
header = get_config_header(self.client, push_registry)
|
||||
@@ -165,12 +163,10 @@ class ImagePusher(DockerBaseClass):
|
||||
except Exception as exc:
|
||||
if 'unauthorized' in str(exc):
|
||||
if 'authentication required' in str(exc):
|
||||
self.client.fail("Error pushing image %s/%s:%s - %s. Try logging into %s first." %
|
||||
(push_registry, push_repo, self.tag, to_native(exc), push_registry))
|
||||
self.client.fail(f"Error pushing image {push_registry}/{push_repo}:{self.tag} - {exc}. Try logging into {push_registry} first.")
|
||||
else:
|
||||
self.client.fail("Error pushing image %s/%s:%s - %s. Does the repository exist?" %
|
||||
(push_registry, push_repo, self.tag, str(exc)))
|
||||
self.client.fail("Error pushing image %s:%s: %s" % (self.name, self.tag, to_native(exc)))
|
||||
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
|
||||
|
||||
@@ -190,10 +186,10 @@ def main():
|
||||
results = ImagePusher(client).push()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -99,8 +99,6 @@ untagged:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -134,7 +132,7 @@ class ImageRemover(DockerBaseClass):
|
||||
self.prune = parameters['prune']
|
||||
|
||||
if not is_valid_tag(self.tag, allow_empty=True):
|
||||
self.fail('"{0}" is not a valid docker tag'.format(self.tag))
|
||||
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):
|
||||
@@ -171,7 +169,7 @@ class ImageRemover(DockerBaseClass):
|
||||
else:
|
||||
image = self.client.find_image(name, self.tag)
|
||||
if self.tag:
|
||||
name = "%s:%s" % (self.name, self.tag)
|
||||
name = f"{self.name}:{self.tag}"
|
||||
|
||||
if self.diff:
|
||||
results['diff'] = dict(before=self.get_diff_state(image))
|
||||
@@ -182,7 +180,7 @@ class ImageRemover(DockerBaseClass):
|
||||
return results
|
||||
|
||||
results['changed'] = True
|
||||
results['actions'].append("Removed image %s" % (name))
|
||||
results['actions'].append(f"Removed image {name}")
|
||||
results['image'] = image
|
||||
|
||||
if not self.check_mode:
|
||||
@@ -192,7 +190,7 @@ class ImageRemover(DockerBaseClass):
|
||||
# If the image vanished while we were trying to remove it, do not fail
|
||||
res = []
|
||||
except Exception as exc:
|
||||
self.fail("Error removing image %s - %s" % (name, to_native(exc)))
|
||||
self.fail(f"Error removing image {name} - {exc}")
|
||||
|
||||
for entry in res:
|
||||
if entry.get('Untagged'):
|
||||
@@ -257,10 +255,10 @@ def main():
|
||||
results = ImageRemover(client).absent()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -102,7 +102,6 @@ tagged_images:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
from ansible.module_utils.common.text.formatters import human_to_bytes
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
@@ -130,7 +129,7 @@ def convert_to_bytes(value, module, name, unlimited_value=None):
|
||||
return unlimited_value
|
||||
return human_to_bytes(value)
|
||||
except ValueError as exc:
|
||||
module.fail_json(msg='Failed to convert %s to bytes: %s' % (name, to_native(exc)))
|
||||
module.fail_json(msg=f'Failed to convert {name} to bytes: {exc}')
|
||||
|
||||
|
||||
def image_info(name, tag, image):
|
||||
@@ -153,7 +152,7 @@ class ImageTagger(DockerBaseClass):
|
||||
self.name = parameters['name']
|
||||
self.tag = parameters['tag']
|
||||
if not is_valid_tag(self.tag, allow_empty=True):
|
||||
self.fail('"{0}" is not a valid docker tag'.format(self.tag))
|
||||
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):
|
||||
@@ -168,12 +167,12 @@ class ImageTagger(DockerBaseClass):
|
||||
self.repositories = []
|
||||
for i, repository in enumerate(parameters['repository']):
|
||||
if is_image_name_id(repository):
|
||||
self.fail("repository[%d] must not be an image ID; got: %s" % (i + 1, repository))
|
||||
self.fail(f"repository[{i + 1}] must not be an image ID; got: {repository}")
|
||||
repo, repo_tag = parse_repository_tag(repository)
|
||||
if not repo_tag:
|
||||
repo_tag = parameters['tag']
|
||||
elif not is_valid_tag(repo_tag, allow_empty=False):
|
||||
self.fail("repository[%d] must not have a digest; got: %s" % (i + 1, repository))
|
||||
self.fail(f"repository[{i + 1}] must not have a digest; got: {repository}")
|
||||
self.repositories.append((repo, repo_tag))
|
||||
|
||||
def fail(self, msg):
|
||||
@@ -186,16 +185,16 @@ class ImageTagger(DockerBaseClass):
|
||||
if tagged_image['Id'] == image['Id']:
|
||||
return (
|
||||
False,
|
||||
"target image already exists (%s) and is as expected" % tagged_image['Id'],
|
||||
f"target image already exists ({tagged_image['Id']}) and is as expected",
|
||||
tagged_image,
|
||||
)
|
||||
if self.keep_existing_images:
|
||||
return (
|
||||
False,
|
||||
"target image already exists (%s) and is not as expected, but kept" % tagged_image['Id'],
|
||||
f"target image already exists ({tagged_image['Id']}) and is not as expected, but kept",
|
||||
tagged_image,
|
||||
)
|
||||
msg = "target image existed (%s) and was not as expected" % tagged_image['Id']
|
||||
msg = f"target image existed ({tagged_image['Id']}) and was not as expected"
|
||||
else:
|
||||
msg = "target image did not exist"
|
||||
|
||||
@@ -211,7 +210,7 @@ class ImageTagger(DockerBaseClass):
|
||||
if res.status_code != 201:
|
||||
raise Exception("Tag operation failed.")
|
||||
except Exception as exc:
|
||||
self.fail("Error: failed to tag image as %s:%s - %s" % (name, tag, to_native(exc)))
|
||||
self.fail(f"Error: failed to tag image as {name}:{tag} - {exc}")
|
||||
|
||||
return True, msg, tagged_image
|
||||
|
||||
@@ -221,7 +220,7 @@ class ImageTagger(DockerBaseClass):
|
||||
else:
|
||||
image = self.client.find_image(name=self.name, tag=self.tag)
|
||||
if not image:
|
||||
self.fail("Cannot find image %s:%s" % (self.name, self.tag))
|
||||
self.fail(f"Cannot find image {self.name}:{self.tag}")
|
||||
|
||||
before = []
|
||||
after = []
|
||||
@@ -239,10 +238,10 @@ class ImageTagger(DockerBaseClass):
|
||||
after.append(image_info(repository, tag, image if tagged else old_image))
|
||||
if tagged:
|
||||
results['changed'] = True
|
||||
results['actions'].append('Tagged image %s as %s:%s: %s' % (image['Id'], repository, tag, msg))
|
||||
tagged_images.append('%s:%s' % (repository, tag))
|
||||
results['actions'].append(f"Tagged image {image['Id']} as {repository}:{tag}: {msg}")
|
||||
tagged_images.append(f'{repository}:{tag}')
|
||||
else:
|
||||
results['actions'].append('Not tagged image %s as %s:%s: %s' % (image['Id'], repository, tag, msg))
|
||||
results['actions'].append(f"Not tagged image {image['Id']} as {repository}:{tag}: {msg}")
|
||||
|
||||
return results
|
||||
|
||||
@@ -264,10 +263,10 @@ def main():
|
||||
results = ImageTagger(client).tag_images()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ import json
|
||||
import os
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_text, to_native
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_text
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
@@ -305,12 +305,12 @@ class LoginManager(DockerBaseClass):
|
||||
:return: None
|
||||
'''
|
||||
|
||||
self.results['actions'].append("Logged into %s" % (self.registry_url))
|
||||
self.log("Log into %s with username %s" % (self.registry_url, self.username))
|
||||
self.results['actions'].append(f"Logged into {self.registry_url}")
|
||||
self.log(f"Log into {self.registry_url} with username {self.username}")
|
||||
try:
|
||||
response = self._login(self.reauthorize)
|
||||
except Exception as exc:
|
||||
self.fail("Logging into %s for user %s failed - %s" % (self.registry_url, self.username, to_native(exc)))
|
||||
self.fail(f"Logging into {self.registry_url} for user {self.username} failed - {exc}")
|
||||
|
||||
# If user is already logged in, then response contains password for user
|
||||
if 'password' in response:
|
||||
@@ -321,7 +321,7 @@ class LoginManager(DockerBaseClass):
|
||||
try:
|
||||
response = self._login(True)
|
||||
except Exception as exc:
|
||||
self.fail("Logging into %s for user %s failed - %s" % (self.registry_url, self.username, to_native(exc)))
|
||||
self.fail(f"Logging into {self.registry_url} for user {self.username} failed - {exc}")
|
||||
response.pop('password', None)
|
||||
self.results['login_result'] = response
|
||||
|
||||
@@ -341,7 +341,7 @@ class LoginManager(DockerBaseClass):
|
||||
store.get(self.registry_url)
|
||||
except CredentialsNotFound:
|
||||
# get raises an exception on not found.
|
||||
self.log("Credentials for %s not present, doing nothing." % (self.registry_url))
|
||||
self.log(f"Credentials for {self.registry_url} not present, doing nothing.")
|
||||
self.results['changed'] = False
|
||||
return
|
||||
|
||||
@@ -372,9 +372,8 @@ class LoginManager(DockerBaseClass):
|
||||
if current['Username'] != self.username or current['Secret'] != self.password or self.reauthorize:
|
||||
if not self.check_mode:
|
||||
store.store(self.registry_url, self.username, self.password)
|
||||
self.log("Writing credentials to configured helper %s for %s" % (store.program, self.registry_url))
|
||||
self.results['actions'].append("Wrote credentials to configured helper %s for %s" % (
|
||||
store.program, self.registry_url))
|
||||
self.log(f"Writing credentials to configured helper {store.program} for {self.registry_url}")
|
||||
self.results['actions'].append(f"Wrote credentials to configured helper {store.program} for {self.registry_url}")
|
||||
self.results['changed'] = True
|
||||
|
||||
def get_credential_store_instance(self, registry, dockercfg_path):
|
||||
@@ -394,7 +393,7 @@ class LoginManager(DockerBaseClass):
|
||||
# Make sure that there is a credential helper before trying to instantiate a
|
||||
# Store object.
|
||||
if store_name:
|
||||
self.log("Found credential store %s" % store_name)
|
||||
self.log(f"Found credential store {store_name}")
|
||||
return Store(store_name, environment=credstore_env)
|
||||
|
||||
return DockerFileStore(dockercfg_path)
|
||||
@@ -435,10 +434,10 @@ def main():
|
||||
del results['actions']
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -355,7 +355,7 @@ def validate_cidr(cidr):
|
||||
return 'ipv4'
|
||||
elif CIDR_IPV6.match(cidr):
|
||||
return 'ipv6'
|
||||
raise ValueError('"{0}" is not a valid CIDR'.format(cidr))
|
||||
raise ValueError(f'"{cidr}" is not a valid CIDR')
|
||||
|
||||
|
||||
def normalize_ipam_config_key(key):
|
||||
@@ -389,8 +389,8 @@ class DockerNetworkManager(object):
|
||||
self.parameters = TaskParameters(client)
|
||||
self.check_mode = self.client.check_mode
|
||||
self.results = {
|
||||
u'changed': False,
|
||||
u'actions': []
|
||||
'changed': False,
|
||||
'actions': []
|
||||
}
|
||||
self.diff = self.client.module._diff
|
||||
self.diff_tracker = DifferenceTracker()
|
||||
@@ -454,7 +454,7 @@ class DockerNetworkManager(object):
|
||||
else:
|
||||
for key, value in self.parameters.driver_options.items():
|
||||
if not (key in net['Options']) or value != net['Options'][key]:
|
||||
differences.add('driver_options.%s' % key,
|
||||
differences.add(f'driver_options.{key}',
|
||||
parameter=value,
|
||||
active=net['Options'].get(key))
|
||||
|
||||
@@ -497,7 +497,7 @@ class DockerNetworkManager(object):
|
||||
# (but have default value None if not specified)
|
||||
continue
|
||||
if value != net_config.get(key):
|
||||
differences.add('ipam_config[%s].%s' % (idx, key),
|
||||
differences.add(f'ipam_config[{idx}].{key}',
|
||||
parameter=value,
|
||||
active=net_config.get(key))
|
||||
|
||||
@@ -536,7 +536,7 @@ class DockerNetworkManager(object):
|
||||
else:
|
||||
for key, value in self.parameters.labels.items():
|
||||
if not (key in net['Labels']) or value != net['Labels'][key]:
|
||||
differences.add('labels.%s' % key,
|
||||
differences.add(f'labels.{key}',
|
||||
parameter=value,
|
||||
active=net['Labels'].get(key))
|
||||
|
||||
@@ -596,7 +596,7 @@ class DockerNetworkManager(object):
|
||||
resp = self.client.post_json_to_json('/networks/create', data=data)
|
||||
self.client.report_warnings(resp, ['Warning'])
|
||||
self.existing_network = self.client.get_network(network_id=resp['Id'])
|
||||
self.results['actions'].append("Created network %s with driver %s" % (self.parameters.name, self.parameters.driver))
|
||||
self.results['actions'].append(f"Created network {self.parameters.name} with driver {self.parameters.driver}")
|
||||
self.results['changed'] = True
|
||||
|
||||
def remove_network(self):
|
||||
@@ -607,7 +607,7 @@ class DockerNetworkManager(object):
|
||||
if self.existing_network.get('Scope', 'local') == 'swarm':
|
||||
while self.get_existing_network():
|
||||
time.sleep(0.1)
|
||||
self.results['actions'].append("Removed network %s" % (self.parameters.name,))
|
||||
self.results['actions'].append(f"Removed network {self.parameters.name}")
|
||||
self.results['changed'] = True
|
||||
|
||||
def is_container_connected(self, container_name):
|
||||
@@ -621,10 +621,10 @@ class DockerNetworkManager(object):
|
||||
return bool(container)
|
||||
|
||||
except DockerException as e:
|
||||
self.client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
self.client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
self.client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
def connect_containers(self):
|
||||
@@ -636,9 +636,9 @@ class DockerNetworkManager(object):
|
||||
"EndpointConfig": None,
|
||||
}
|
||||
self.client.post_json('/networks/{0}/connect', self.parameters.name, data=data)
|
||||
self.results['actions'].append("Connected container %s" % (name,))
|
||||
self.results['actions'].append(f"Connected container {name}")
|
||||
self.results['changed'] = True
|
||||
self.diff_tracker.add('connected.{0}'.format(name), parameter=True, active=False)
|
||||
self.diff_tracker.add(f'connected.{name}', parameter=True, active=False)
|
||||
|
||||
def disconnect_missing(self):
|
||||
if not self.existing_network:
|
||||
@@ -662,9 +662,9 @@ class DockerNetworkManager(object):
|
||||
if not self.check_mode:
|
||||
data = {"Container": container_name, "Force": True}
|
||||
self.client.post_json('/networks/{0}/disconnect', self.parameters.name, data=data)
|
||||
self.results['actions'].append("Disconnected container %s" % (container_name,))
|
||||
self.results['actions'].append(f"Disconnected container {container_name}")
|
||||
self.results['changed'] = True
|
||||
self.diff_tracker.add('connected.{0}'.format(container_name),
|
||||
self.diff_tracker.add(f'connected.{container_name}',
|
||||
parameter=False,
|
||||
active=True)
|
||||
|
||||
@@ -747,10 +747,10 @@ def main():
|
||||
cm = DockerNetworkManager(client)
|
||||
client.module.exit_json(**cm.results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -98,8 +98,6 @@ network:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -126,10 +124,10 @@ def main():
|
||||
network=network,
|
||||
)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -198,7 +198,7 @@ class SwarmNodeManager(DockerBaseClass):
|
||||
try:
|
||||
node_info = self.client.inspect_node(node_id=self.parameters.hostname)
|
||||
except APIError as exc:
|
||||
self.client.fail("Failed to get node information for %s" % to_native(exc))
|
||||
self.client.fail(f"Failed to get node information for {exc}")
|
||||
|
||||
changed = False
|
||||
node_spec = dict(
|
||||
@@ -247,9 +247,8 @@ class SwarmNodeManager(DockerBaseClass):
|
||||
changed = True
|
||||
else:
|
||||
self.client.module.warn(
|
||||
"Label '%s' listed both in 'labels' and 'labels_to_remove'. "
|
||||
"Keeping the assigned label value."
|
||||
% to_native(key))
|
||||
f"Label '{to_native(key)}' listed both in 'labels' and 'labels_to_remove'. "
|
||||
"Keeping the assigned label value.")
|
||||
else:
|
||||
if node_spec['Labels'].get(key):
|
||||
node_spec['Labels'].pop(key)
|
||||
@@ -261,7 +260,7 @@ class SwarmNodeManager(DockerBaseClass):
|
||||
self.client.update_node(node_id=node_info['ID'], version=node_info['Version']['Index'],
|
||||
node_spec=node_spec)
|
||||
except APIError as exc:
|
||||
self.client.fail("Failed to update node : %s" % to_native(exc))
|
||||
self.client.fail(f"Failed to update node : {exc}")
|
||||
self.results['node'] = self.client.get_node_inspect(node_id=node_info['ID'])
|
||||
self.results['changed'] = changed
|
||||
else:
|
||||
@@ -293,10 +292,10 @@ def main():
|
||||
SwarmNodeManager(client, results)
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -88,8 +88,6 @@ nodes:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common import (
|
||||
RequestException,
|
||||
)
|
||||
@@ -149,10 +147,10 @@ def main():
|
||||
nodes=nodes,
|
||||
)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ class TaskParameters(DockerBaseClass):
|
||||
|
||||
|
||||
def prepare_options(options):
|
||||
return ['%s=%s' % (k, v if v is not None else "") for k, v in options.items()] if options else []
|
||||
return [f'{k}={v if v is not None else ""}' for k, v in options.items()] if options else []
|
||||
|
||||
|
||||
def parse_options(options_list):
|
||||
@@ -227,7 +227,7 @@ class DockerPluginManager(object):
|
||||
if ((not existing_options.get(key) and value) or
|
||||
not value or
|
||||
value != existing_options[key]):
|
||||
differences.add('plugin_options.%s' % key,
|
||||
differences.add(f'plugin_options.{key}',
|
||||
parameter=value,
|
||||
active=existing_options.get(key))
|
||||
|
||||
@@ -262,7 +262,7 @@ class DockerPluginManager(object):
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
|
||||
self.actions.append("Installed plugin %s" % self.preferred_name)
|
||||
self.actions.append(f"Installed plugin {self.preferred_name}")
|
||||
self.changed = True
|
||||
|
||||
def remove_plugin(self):
|
||||
@@ -274,7 +274,7 @@ class DockerPluginManager(object):
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
|
||||
self.actions.append("Removed plugin %s" % self.preferred_name)
|
||||
self.actions.append(f"Removed plugin {self.preferred_name}")
|
||||
self.changed = True
|
||||
|
||||
def update_plugin(self):
|
||||
@@ -287,7 +287,7 @@ class DockerPluginManager(object):
|
||||
self.client.post_json('/plugins/{0}/set', self.preferred_name, data=data)
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
self.actions.append("Updated plugin %s settings" % self.preferred_name)
|
||||
self.actions.append(f"Updated plugin {self.preferred_name} settings")
|
||||
self.changed = True
|
||||
else:
|
||||
self.client.fail("Cannot update the plugin: Plugin does not exist")
|
||||
@@ -322,7 +322,7 @@ class DockerPluginManager(object):
|
||||
self.client.post_json('/plugins/{0}/enable', self.preferred_name, params={'timeout': timeout})
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
self.actions.append("Enabled plugin %s" % self.preferred_name)
|
||||
self.actions.append(f"Enabled plugin {self.preferred_name}")
|
||||
self.changed = True
|
||||
else:
|
||||
self.install_plugin()
|
||||
@@ -331,7 +331,7 @@ class DockerPluginManager(object):
|
||||
self.client.post_json('/plugins/{0}/enable', self.preferred_name, params={'timeout': timeout})
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
self.actions.append("Enabled plugin %s" % self.preferred_name)
|
||||
self.actions.append(f"Enabled plugin {self.preferred_name}")
|
||||
self.changed = True
|
||||
|
||||
def disable(self):
|
||||
@@ -342,7 +342,7 @@ class DockerPluginManager(object):
|
||||
self.client.post_json('/plugins/{0}/disable', self.preferred_name)
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
self.actions.append("Disable plugin %s" % self.preferred_name)
|
||||
self.actions.append(f"Disable plugin {self.preferred_name}")
|
||||
self.changed = True
|
||||
else:
|
||||
self.client.fail("Plugin not found: Plugin does not exist.")
|
||||
@@ -384,10 +384,10 @@ def main():
|
||||
cm = DockerPluginManager(client)
|
||||
client.module.exit_json(**cm.result)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -230,7 +230,6 @@ builder_cache_caches_deleted:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
from ansible.module_utils.common.text.formatters import human_to_bytes
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
@@ -276,7 +275,7 @@ def main():
|
||||
try:
|
||||
builder_cache_keep_storage = human_to_bytes(client.module.params.get('builder_cache_keep_storage'))
|
||||
except ValueError as exc:
|
||||
client.module.fail_json(msg='Error while parsing value of builder_cache_keep_storage: {0}'.format(exc))
|
||||
client.module.fail_json(msg=f'Error while parsing value of builder_cache_keep_storage: {exc}')
|
||||
|
||||
try:
|
||||
result = dict()
|
||||
@@ -337,10 +336,10 @@ def main():
|
||||
result['changed'] = changed
|
||||
client.module.exit_json(**result)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -206,7 +206,7 @@ from ansible_collections.community.docker.plugins.module_utils.util import (
|
||||
compare_generic,
|
||||
sanitize_labels,
|
||||
)
|
||||
from ansible.module_utils.common.text.converters import to_native, to_bytes
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
|
||||
|
||||
class SecretManager(DockerBaseClass):
|
||||
@@ -234,7 +234,7 @@ class SecretManager(DockerBaseClass):
|
||||
with open(data_src, 'rb') as f:
|
||||
self.data = f.read()
|
||||
except Exception as exc:
|
||||
self.client.fail('Error while reading {src}: {error}'.format(src=data_src, error=to_native(exc)))
|
||||
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')
|
||||
@@ -272,13 +272,13 @@ class SecretManager(DockerBaseClass):
|
||||
try:
|
||||
secrets = self.client.secrets(filters={'name': self.name})
|
||||
except APIError as exc:
|
||||
self.client.fail("Error accessing secret %s: %s" % (self.name, to_native(exc)))
|
||||
self.client.fail(f"Error accessing secret {self.name}: {exc}")
|
||||
|
||||
if self.rolling_versions:
|
||||
self.secrets = [
|
||||
secret
|
||||
for secret in secrets
|
||||
if secret['Spec']['Name'].startswith('{name}_v'.format(name=self.name))
|
||||
if secret['Spec']['Name'].startswith(f'{self.name}_v')
|
||||
]
|
||||
self.secrets.sort(key=self.get_version)
|
||||
else:
|
||||
@@ -296,7 +296,7 @@ class SecretManager(DockerBaseClass):
|
||||
if self.rolling_versions:
|
||||
self.version += 1
|
||||
labels['ansible_version'] = str(self.version)
|
||||
self.name = '{name}_v{version}'.format(name=self.name, version=self.version)
|
||||
self.name = f'{self.name}_v{self.version}'
|
||||
if self.labels:
|
||||
labels.update(self.labels)
|
||||
|
||||
@@ -305,7 +305,7 @@ class SecretManager(DockerBaseClass):
|
||||
secret_id = self.client.create_secret(self.name, self.data, labels=labels)
|
||||
self.secrets += self.client.secrets(filters={'id': secret_id})
|
||||
except APIError as exc:
|
||||
self.client.fail("Error creating secret: %s" % to_native(exc))
|
||||
self.client.fail(f"Error creating secret: {exc}")
|
||||
|
||||
if isinstance(secret_id, dict):
|
||||
secret_id = secret_id['ID']
|
||||
@@ -317,7 +317,7 @@ class SecretManager(DockerBaseClass):
|
||||
if not self.check_mode:
|
||||
self.client.remove_secret(secret['ID'])
|
||||
except APIError as exc:
|
||||
self.client.fail("Error removing secret %s: %s" % (secret['Spec']['Name'], to_native(exc)))
|
||||
self.client.fail(f"Error removing secret {secret['Spec']['Name']}: {exc}")
|
||||
|
||||
def present(self):
|
||||
''' Handles state == 'present', creating or updating the secret '''
|
||||
@@ -397,10 +397,10 @@ def main():
|
||||
SecretManager(client, results)()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ stack_spec_diff:
|
||||
definition.
|
||||
sample: >
|
||||
"stack_spec_diff":
|
||||
{'test_stack_test_service': {u'TaskTemplate': {u'ContainerSpec': {delete: [u'Env']}}}}
|
||||
{'test_stack_test_service': {'TaskTemplate': {'ContainerSpec': {delete: ['Env']}}}}
|
||||
returned: on change
|
||||
type: dict
|
||||
"""
|
||||
@@ -184,7 +184,7 @@ except ImportError:
|
||||
|
||||
def docker_stack_services(client, stack_name):
|
||||
rc, out, err = client.call_cli("stack", "services", stack_name, "--format", "{{.Name}}")
|
||||
if to_native(err) == "Nothing found in stack: %s\n" % stack_name:
|
||||
if to_native(err) == f"Nothing found in stack: {stack_name}\n":
|
||||
return []
|
||||
return to_native(out).strip().split('\n')
|
||||
|
||||
@@ -230,7 +230,7 @@ def docker_stack_rm(client, stack_name, retries, interval):
|
||||
command += ["--detach=false"]
|
||||
rc, out, err = client.call_cli(*command)
|
||||
|
||||
while to_native(err) != "Nothing found in stack: %s\n" % stack_name and retries > 0:
|
||||
while to_native(err) != f"Nothing found in stack: {stack_name}\n" and retries > 0:
|
||||
sleep(interval)
|
||||
retries = retries - 1
|
||||
rc, out, err = client.call_cli(*command)
|
||||
@@ -281,7 +281,7 @@ def main():
|
||||
elif isinstance(compose_def, str):
|
||||
compose_files.append(compose_def)
|
||||
else:
|
||||
client.fail("compose element '%s' must be a string or a dictionary" % compose_def)
|
||||
client.fail(f"compose element '{compose_def}' must be a string or a dictionary")
|
||||
|
||||
before_stack_services = docker_stack_inspect(client, name)
|
||||
|
||||
@@ -340,7 +340,7 @@ def main():
|
||||
)
|
||||
client.module.exit_json(changed=False)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -110,7 +110,7 @@ def main():
|
||||
results=ret,
|
||||
)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -120,7 +120,7 @@ def main():
|
||||
results=ret,
|
||||
)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -309,8 +309,6 @@ from ansible_collections.community.docker.plugins.module_utils.util import (
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.swarm import AnsibleDockerSwarmClient
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
|
||||
class TaskParameters(DockerBaseClass):
|
||||
def __init__(self):
|
||||
@@ -531,7 +529,7 @@ class SwarmManager(DockerBaseClass):
|
||||
try:
|
||||
self.client.init_swarm(**init_arguments)
|
||||
except APIError as exc:
|
||||
self.client.fail("Can not create a new Swarm Cluster: %s" % to_native(exc))
|
||||
self.client.fail(f"Can not create a new Swarm Cluster: {exc}")
|
||||
|
||||
if not self.client.check_if_swarm_manager():
|
||||
if not self.check_mode:
|
||||
@@ -539,7 +537,7 @@ class SwarmManager(DockerBaseClass):
|
||||
|
||||
self.created = True
|
||||
self.inspect_swarm()
|
||||
self.results['actions'].append("New Swarm cluster created: %s" % (self.swarm_info.get('ID')))
|
||||
self.results['actions'].append(f"New Swarm cluster created: {self.swarm_info.get('ID')}")
|
||||
self.differences.add('state', parameter='present', active='absent')
|
||||
self.results['changed'] = True
|
||||
self.results['swarm_facts'] = {
|
||||
@@ -567,7 +565,7 @@ class SwarmManager(DockerBaseClass):
|
||||
rotate_worker_token=self.parameters.rotate_worker_token,
|
||||
rotate_manager_token=self.parameters.rotate_manager_token)
|
||||
except APIError as exc:
|
||||
self.client.fail("Can not update a Swarm Cluster: %s" % to_native(exc))
|
||||
self.client.fail(f"Can not update a Swarm Cluster: {exc}")
|
||||
return
|
||||
|
||||
self.inspect_swarm()
|
||||
@@ -590,7 +588,7 @@ class SwarmManager(DockerBaseClass):
|
||||
try:
|
||||
self.client.join_swarm(**join_arguments)
|
||||
except APIError as exc:
|
||||
self.client.fail("Can not join the Swarm Cluster: %s" % to_native(exc))
|
||||
self.client.fail(f"Can not join the Swarm Cluster: {exc}")
|
||||
self.results['actions'].append("New node is added to swarm cluster")
|
||||
self.differences.add('joined', parameter=True, active=False)
|
||||
self.results['changed'] = True
|
||||
@@ -603,7 +601,7 @@ class SwarmManager(DockerBaseClass):
|
||||
try:
|
||||
self.client.leave_swarm(force=self.force)
|
||||
except APIError as exc:
|
||||
self.client.fail("This node can not leave the Swarm Cluster: %s" % to_native(exc))
|
||||
self.client.fail(f"This node can not leave the Swarm Cluster: {exc}")
|
||||
self.results['actions'].append("Node has left the swarm cluster")
|
||||
self.differences.add('joined', parameter='absent', active='present')
|
||||
self.results['changed'] = True
|
||||
@@ -624,7 +622,7 @@ class SwarmManager(DockerBaseClass):
|
||||
try:
|
||||
self.client.remove_node(node_id=self.node_id, force=self.force)
|
||||
except APIError as exc:
|
||||
self.client.fail("Can not remove the node from the Swarm Cluster: %s" % to_native(exc))
|
||||
self.client.fail(f"Can not remove the node from the Swarm Cluster: {exc}")
|
||||
self.results['actions'].append("Node is removed from swarm cluster.")
|
||||
self.differences.add('joined', parameter=False, active=True)
|
||||
self.results['changed'] = True
|
||||
@@ -707,10 +705,10 @@ def main():
|
||||
SwarmManager(client, results)()
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -192,8 +192,6 @@ except ImportError:
|
||||
# missing Docker SDK for Python handled in ansible.module_utils.docker_common
|
||||
pass
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.swarm import AnsibleDockerSwarmClient
|
||||
from ansible_collections.community.docker.plugins.module_utils.common import RequestException
|
||||
from ansible_collections.community.docker.plugins.module_utils.util import (
|
||||
@@ -231,7 +229,7 @@ class DockerSwarmManager(DockerBaseClass):
|
||||
try:
|
||||
return self.client.inspect_swarm()
|
||||
except APIError as exc:
|
||||
self.client.fail("Error inspecting docker swarm: %s" % to_native(exc))
|
||||
self.client.fail(f"Error inspecting docker swarm: {exc}")
|
||||
|
||||
def get_docker_items_list(self, docker_object=None, filters=None):
|
||||
items = None
|
||||
@@ -245,8 +243,7 @@ class DockerSwarmManager(DockerBaseClass):
|
||||
elif docker_object == 'services':
|
||||
items = self.client.services(filters=filters)
|
||||
except APIError as exc:
|
||||
self.client.fail("Error inspecting docker swarm for object '%s': %s" %
|
||||
(docker_object, to_native(exc)))
|
||||
self.client.fail(f"Error inspecting docker swarm for object '{docker_object}': {exc}")
|
||||
|
||||
if self.verbose_output:
|
||||
return items
|
||||
@@ -367,10 +364,10 @@ def main():
|
||||
results.update(client.fail_results)
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -869,7 +869,7 @@ from ansible_collections.community.docker.plugins.module_utils.util import (
|
||||
)
|
||||
|
||||
from ansible.module_utils.basic import human_to_bytes
|
||||
from ansible.module_utils.common.text.converters import to_text, to_native
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
|
||||
try:
|
||||
from docker import types
|
||||
@@ -909,7 +909,7 @@ def get_docker_environment(env, env_files):
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(
|
||||
'Non-string value found for env option. '
|
||||
'Ambiguous env options must be wrapped in quotes to avoid YAML parsing. Key: %s' % name
|
||||
f'Ambiguous env options must be wrapped in quotes to avoid YAML parsing. Key: {name}'
|
||||
)
|
||||
env_dict[name] = str(value)
|
||||
elif env is not None and isinstance(env, list):
|
||||
@@ -921,7 +921,7 @@ def get_docker_environment(env, env_files):
|
||||
env_dict[name] = value
|
||||
elif env is not None:
|
||||
raise ValueError(
|
||||
'Invalid type for env %s (%s). Only list or dict allowed.' % (env, type(env))
|
||||
f'Invalid type for env {env} ({type(env)}). Only list or dict allowed.'
|
||||
)
|
||||
env_list = format_environment(env_dict)
|
||||
if not env_list:
|
||||
@@ -968,7 +968,7 @@ def get_docker_networks(networks, network_ids):
|
||||
if network:
|
||||
invalid_keys = ', '.join(network.keys())
|
||||
raise TypeError(
|
||||
'%s are not valid keys for the networks option' % invalid_keys
|
||||
f'{invalid_keys} are not valid keys for the networks option'
|
||||
)
|
||||
|
||||
else:
|
||||
@@ -979,7 +979,7 @@ def get_docker_networks(networks, network_ids):
|
||||
try:
|
||||
parsed_network['id'] = network_ids[network_name]
|
||||
except KeyError as e:
|
||||
raise ValueError('Could not find a network named: %s.' % e)
|
||||
raise ValueError(f'Could not find a network named: {e}.')
|
||||
parsed_networks.append(parsed_network)
|
||||
return parsed_networks or []
|
||||
|
||||
@@ -996,8 +996,7 @@ def get_nanoseconds_from_raw_option(name, value):
|
||||
return convert_duration_to_nanosecond(value)
|
||||
else:
|
||||
raise ValueError(
|
||||
'Invalid type for %s %s (%s). Only string or int allowed.'
|
||||
% (name, value, type(value))
|
||||
f'Invalid type for {name} {value} ({type(value)}). Only string or int allowed.'
|
||||
)
|
||||
|
||||
|
||||
@@ -1385,7 +1384,7 @@ class DockerService(DockerBaseClass):
|
||||
try:
|
||||
memory = human_to_bytes(memory)
|
||||
except ValueError as exc:
|
||||
raise Exception('Failed to convert limit_memory to bytes: %s' % exc)
|
||||
raise Exception(f'Failed to convert limit_memory to bytes: {exc}')
|
||||
return {
|
||||
'limit_cpu': cpus,
|
||||
'limit_memory': memory,
|
||||
@@ -1407,7 +1406,7 @@ class DockerService(DockerBaseClass):
|
||||
try:
|
||||
memory = human_to_bytes(memory)
|
||||
except ValueError as exc:
|
||||
raise Exception('Failed to convert reserve_memory to bytes: %s' % exc)
|
||||
raise Exception(f'Failed to convert reserve_memory to bytes: {exc}')
|
||||
return {
|
||||
'reserve_cpu': cpus,
|
||||
'reserve_memory': memory,
|
||||
@@ -1483,21 +1482,19 @@ class DockerService(DockerBaseClass):
|
||||
if invalid_items:
|
||||
errors = ', '.join(
|
||||
[
|
||||
'%s (%s) at index %s' % (item, type(item), index)
|
||||
f'{item} ({type(item)}) at index {index}'
|
||||
for index, item in invalid_items
|
||||
]
|
||||
)
|
||||
raise Exception(
|
||||
'All items in a command list need to be strings. '
|
||||
'Check quoting. Invalid items: %s.'
|
||||
% errors
|
||||
f'Check quoting. Invalid items: {errors}.'
|
||||
)
|
||||
s.command = ap['command']
|
||||
elif s.command is not None:
|
||||
raise ValueError(
|
||||
'Invalid type for command %s (%s). '
|
||||
f'Invalid type for command {s.command} ({type(s.command)}). '
|
||||
'Only string or list allowed. Check quoting.'
|
||||
% (s.command, type(s.command))
|
||||
)
|
||||
|
||||
s.env = get_docker_environment(ap['env'], ap['env_files'])
|
||||
@@ -1577,7 +1574,7 @@ class DockerService(DockerBaseClass):
|
||||
tmpfs_size = human_to_bytes(tmpfs_size)
|
||||
except ValueError as exc:
|
||||
raise ValueError(
|
||||
'Failed to convert tmpfs_size to bytes: %s' % exc
|
||||
f'Failed to convert tmpfs_size to bytes: {exc}'
|
||||
)
|
||||
|
||||
service_m['tmpfs_size'] = tmpfs_size
|
||||
@@ -2214,7 +2211,7 @@ class DockerServiceManager(object):
|
||||
ds.mode = to_text('replicated-job', encoding='utf-8')
|
||||
ds.replicas = mode['ReplicatedJob']['TotalCompletions']
|
||||
else:
|
||||
raise Exception('Unknown service mode: %s' % mode)
|
||||
raise Exception(f'Unknown service mode: {mode}')
|
||||
|
||||
raw_data_mounts = task_template_data['ContainerSpec'].get('Mounts')
|
||||
if raw_data_mounts:
|
||||
@@ -2314,7 +2311,7 @@ class DockerServiceManager(object):
|
||||
name = repo + ':' + tag
|
||||
distribution_data = self.client.inspect_distribution(name)
|
||||
digest = distribution_data['Descriptor']['digest']
|
||||
return '%s@%s' % (name, digest)
|
||||
return f'{name}@{digest}'
|
||||
|
||||
def get_networks_names_ids(self):
|
||||
return dict(
|
||||
@@ -2341,7 +2338,7 @@ class DockerServiceManager(object):
|
||||
for secret_name in secret_names:
|
||||
if secret_name not in secrets:
|
||||
self.client.fail(
|
||||
'Could not find a secret named "%s"' % secret_name
|
||||
f'Could not find a secret named "{secret_name}"'
|
||||
)
|
||||
return secrets
|
||||
|
||||
@@ -2365,7 +2362,7 @@ class DockerServiceManager(object):
|
||||
for config_name in config_names:
|
||||
if config_name not in configs:
|
||||
self.client.fail(
|
||||
'Could not find a config named "%s"' % config_name
|
||||
f'Could not find a config named "{config_name}"'
|
||||
)
|
||||
return configs
|
||||
|
||||
@@ -2381,16 +2378,14 @@ class DockerServiceManager(object):
|
||||
)
|
||||
except DockerException as e:
|
||||
self.client.fail(
|
||||
'Error looking for an image named %s: %s'
|
||||
% (image, to_native(e))
|
||||
f'Error looking for an image named {image}: {e}'
|
||||
)
|
||||
|
||||
try:
|
||||
current_service = self.get_service(module.params['name'])
|
||||
except Exception as e:
|
||||
self.client.fail(
|
||||
'Error looking for service named %s: %s'
|
||||
% (module.params['name'], to_native(e))
|
||||
f"Error looking for service named {module.params['name']}: {e}"
|
||||
)
|
||||
try:
|
||||
secret_ids = self.get_missing_secret_ids()
|
||||
@@ -2407,7 +2402,7 @@ class DockerServiceManager(object):
|
||||
)
|
||||
except Exception as e:
|
||||
return self.client.fail(
|
||||
'Error parsing module parameters: %s' % to_native(e)
|
||||
f'Error parsing module parameters: {e}'
|
||||
)
|
||||
|
||||
changed = False
|
||||
@@ -2792,10 +2787,10 @@ def main():
|
||||
|
||||
client.module.exit_json(**results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -64,8 +64,6 @@ service:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
try:
|
||||
from docker.errors import DockerException
|
||||
except ImportError:
|
||||
@@ -109,10 +107,10 @@ def main():
|
||||
exists=bool(service)
|
||||
)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -159,8 +159,8 @@ class DockerVolumeManager(object):
|
||||
self.parameters = TaskParameters(client)
|
||||
self.check_mode = self.client.check_mode
|
||||
self.results = {
|
||||
u'changed': False,
|
||||
u'actions': []
|
||||
'changed': False,
|
||||
'actions': []
|
||||
}
|
||||
self.diff = self.client.module._diff
|
||||
self.diff_tracker = DifferenceTracker()
|
||||
@@ -185,10 +185,10 @@ class DockerVolumeManager(object):
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
|
||||
if volumes[u'Volumes'] is None:
|
||||
if volumes['Volumes'] is None:
|
||||
return None
|
||||
|
||||
for volume in volumes[u'Volumes']:
|
||||
for volume in volumes['Volumes']:
|
||||
if volume['Name'] == self.parameters.volume_name:
|
||||
return volume
|
||||
|
||||
@@ -212,14 +212,14 @@ class DockerVolumeManager(object):
|
||||
for key, value in self.parameters.driver_options.items():
|
||||
if (not self.existing_volume['Options'].get(key) or
|
||||
value != self.existing_volume['Options'][key]):
|
||||
differences.add('driver_options.%s' % key,
|
||||
differences.add(f'driver_options.{key}',
|
||||
parameter=value,
|
||||
active=self.existing_volume['Options'].get(key))
|
||||
if self.parameters.labels:
|
||||
existing_labels = self.existing_volume.get('Labels') or {}
|
||||
for label in self.parameters.labels:
|
||||
if existing_labels.get(label) != self.parameters.labels.get(label):
|
||||
differences.add('labels.%s' % label,
|
||||
differences.add(f'labels.{label}',
|
||||
parameter=self.parameters.labels.get(label),
|
||||
active=existing_labels.get(label))
|
||||
|
||||
@@ -241,7 +241,7 @@ class DockerVolumeManager(object):
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
|
||||
self.results['actions'].append("Created volume %s with driver %s" % (self.parameters.volume_name, self.parameters.driver))
|
||||
self.results['actions'].append(f"Created volume {self.parameters.volume_name} with driver {self.parameters.driver}")
|
||||
self.results['changed'] = True
|
||||
|
||||
def remove_volume(self):
|
||||
@@ -252,7 +252,7 @@ class DockerVolumeManager(object):
|
||||
except APIError as e:
|
||||
self.client.fail(to_native(e))
|
||||
|
||||
self.results['actions'].append("Removed volume %s" % self.parameters.volume_name)
|
||||
self.results['actions'].append(f"Removed volume {self.parameters.volume_name}")
|
||||
self.results['changed'] = True
|
||||
|
||||
def present(self):
|
||||
@@ -304,10 +304,10 @@ def main():
|
||||
cm = DockerVolumeManager(client)
|
||||
client.module.exit_json(**cm.results)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@@ -72,8 +72,6 @@ volume:
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
AnsibleDockerClient,
|
||||
RequestException,
|
||||
@@ -87,7 +85,7 @@ def get_existing_volume(client, volume_name):
|
||||
except NotFound as dummy:
|
||||
return None
|
||||
except Exception as exc:
|
||||
client.fail("Error inspecting volume: %s" % to_native(exc))
|
||||
client.fail(f"Error inspecting volume: {exc}")
|
||||
|
||||
|
||||
def main():
|
||||
@@ -109,10 +107,10 @@ def main():
|
||||
volume=volume,
|
||||
)
|
||||
except DockerException as e:
|
||||
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
|
||||
client.fail(f'An unexpected Docker error occurred: {e}', exception=traceback.format_exc())
|
||||
except RequestException as e:
|
||||
client.fail(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}',
|
||||
exception=traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user