mirror of
https://github.com/ansible-collections/community.docker.git
synced 2026-07-31 20:53:49 +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:
@@ -12,7 +12,7 @@ import shlex
|
||||
|
||||
from functools import partial
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native, to_text
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.module_utils.common.text.formatters import human_to_bytes
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.util import (
|
||||
@@ -56,7 +56,7 @@ def _get_ansible_type(type):
|
||||
if type == 'set':
|
||||
return 'list'
|
||||
if type not in ('list', 'dict', 'bool', 'int', 'float', 'str'):
|
||||
raise Exception('Invalid type "%s"' % (type, ))
|
||||
raise Exception(f'Invalid type "{type}"')
|
||||
return type
|
||||
|
||||
|
||||
@@ -365,15 +365,15 @@ def _parse_port_range(range_or_port, module):
|
||||
try:
|
||||
start, end = [int(port) for port in range_or_port.split('-')]
|
||||
except Exception:
|
||||
module.fail_json(msg='Invalid port range: "{0}"'.format(range_or_port))
|
||||
module.fail_json(msg=f'Invalid port range: "{range_or_port}"')
|
||||
if end < start:
|
||||
module.fail_json(msg='Invalid port range: "{0}"'.format(range_or_port))
|
||||
module.fail_json(msg=f'Invalid port range: "{range_or_port}"')
|
||||
return list(range(start, end + 1))
|
||||
else:
|
||||
try:
|
||||
return [int(range_or_port)]
|
||||
except Exception:
|
||||
module.fail_json(msg='Invalid port: "{0}"'.format(range_or_port))
|
||||
module.fail_json(msg=f'Invalid port: "{range_or_port}"')
|
||||
|
||||
|
||||
def _split_colon_ipv6(text, module):
|
||||
@@ -391,7 +391,7 @@ def _split_colon_ipv6(text, module):
|
||||
break
|
||||
j = text.find(']', i)
|
||||
if j < 0:
|
||||
module.fail_json(msg='Cannot find closing "]" in input "{0}" for opening "[" at index {1}!'.format(text, i + 1))
|
||||
module.fail_json(msg=f'Cannot find closing "]" in input "{text}" for opening "[" at index {i + 1}!')
|
||||
result.extend(text[start:i].split(':'))
|
||||
k = text.find(':', j)
|
||||
if k < 0:
|
||||
@@ -461,11 +461,11 @@ def _preprocess_env(module, values):
|
||||
for name, value in values['env'].items():
|
||||
if not isinstance(value, str):
|
||||
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}')
|
||||
final_env[name] = to_text(value, errors='surrogate_or_strict')
|
||||
formatted_env = []
|
||||
for key, value in final_env.items():
|
||||
formatted_env.append('%s=%s' % (key, value))
|
||||
formatted_env.append(f'{key}={value}')
|
||||
return {
|
||||
'env': formatted_env,
|
||||
}
|
||||
@@ -491,7 +491,7 @@ def _preprocess_convert_to_bytes(module, values, name, unlimited_value=None):
|
||||
values[name] = value
|
||||
return values
|
||||
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 _preprocess_mac_address(module, values):
|
||||
@@ -571,9 +571,9 @@ def _preprocess_mounts(module, values):
|
||||
def check_collision(t, name):
|
||||
if t in last:
|
||||
if name == last[t]:
|
||||
module.fail_json(msg='The mount point "{0}" appears twice in the {1} option'.format(t, name))
|
||||
module.fail_json(msg=f'The mount point "{t}" appears twice in the {name} option')
|
||||
else:
|
||||
module.fail_json(msg='The mount point "{0}" appears both in the {1} and {2} option'.format(t, name, last[t]))
|
||||
module.fail_json(msg=f'The mount point "{t}" appears both in the {name} and {last[t]} option')
|
||||
last[t] = name
|
||||
|
||||
if 'mounts' in values:
|
||||
@@ -588,17 +588,13 @@ def _preprocess_mounts(module, values):
|
||||
|
||||
# Sanity checks
|
||||
if mount['source'] is None and mount_type not in ('tmpfs', 'volume', 'image', 'cluster'):
|
||||
module.fail_json(msg='source must be specified for mount "{0}" of type "{1}"'.format(target, mount_type))
|
||||
module.fail_json(msg=f'source must be specified for mount "{target}" of type "{mount_type}"')
|
||||
for option, req_mount_types in _MOUNT_OPTION_TYPES.items():
|
||||
if mount[option] is not None and mount_type not in req_mount_types:
|
||||
type_plural = "" if len(req_mount_types) == 1 else "s"
|
||||
type_list = '", "'.join(req_mount_types)
|
||||
module.fail_json(
|
||||
msg='{0} cannot be specified for mount "{1}" of type "{2}" (needs type{3} "{4}")'.format(
|
||||
option,
|
||||
target,
|
||||
mount_type,
|
||||
"" if len(req_mount_types) == 1 else "s",
|
||||
'", "'.join(req_mount_types),
|
||||
)
|
||||
msg=f'{option} cannot be specified for mount "{target}" of type "{mount_type}" (needs type{type_plural} "{type_list}")'
|
||||
)
|
||||
|
||||
# Streamline options
|
||||
@@ -611,22 +607,22 @@ def _preprocess_mounts(module, values):
|
||||
try:
|
||||
mount_dict['tmpfs_size'] = human_to_bytes(mount_dict['tmpfs_size'])
|
||||
except ValueError as exc:
|
||||
module.fail_json(msg='Failed to convert tmpfs_size of mount "{0}" to bytes: {1}'.format(target, to_native(exc)))
|
||||
module.fail_json(msg=f'Failed to convert tmpfs_size of mount "{target}" to bytes: {exc}')
|
||||
if mount_dict['tmpfs_mode'] is not None:
|
||||
try:
|
||||
mount_dict['tmpfs_mode'] = int(mount_dict['tmpfs_mode'], 8)
|
||||
except Exception as dummy:
|
||||
module.fail_json(msg='tmp_fs mode of mount "{0}" is not an octal string!'.format(target))
|
||||
module.fail_json(msg=f'tmp_fs mode of mount "{target}" is not an octal string!')
|
||||
if mount_dict['tmpfs_options']:
|
||||
opts = []
|
||||
for idx, opt in enumerate(mount_dict['tmpfs_options']):
|
||||
if len(opt) != 1:
|
||||
module.fail_json(msg='tmpfs_options[{1}] of mount "{0}" must be a one-element dictionary!'.format(target, idx + 1))
|
||||
module.fail_json(msg=f'tmpfs_options[{idx + 1}] of mount "{target}" must be a one-element dictionary!')
|
||||
k, v = list(opt.items())[0]
|
||||
if not isinstance(k, str):
|
||||
module.fail_json(msg='key {2!r} in tmpfs_options[{1}] of mount "{0}" must be a string!'.format(target, idx + 1, k))
|
||||
module.fail_json(msg=f'key {k!r} in tmpfs_options[{idx + 1}] of mount "{target}" must be a string!')
|
||||
if v is not None and not isinstance(v, str):
|
||||
module.fail_json(msg='value {2!r} in tmpfs_options[{1}] of mount "{0}" must be a string or null/none!'.format(target, idx + 1, v))
|
||||
module.fail_json(msg=f'value {v!r} in tmpfs_options[{idx + 1}] of mount "{target}" must be a string or null/none!')
|
||||
opts.append([k, v] if v is not None else [k])
|
||||
mount_dict['tmpfs_options'] = opts
|
||||
|
||||
@@ -641,17 +637,17 @@ def _preprocess_mounts(module, values):
|
||||
if len(parts) == 3:
|
||||
host, container, mode = parts
|
||||
if not _is_volume_permissions(mode):
|
||||
module.fail_json(msg='Found invalid volumes mode: {0}'.format(mode))
|
||||
module.fail_json(msg=f'Found invalid volumes mode: {mode}')
|
||||
if re.match(r'[.~]', host):
|
||||
host = os.path.abspath(os.path.expanduser(host))
|
||||
check_collision(container, 'volumes')
|
||||
new_vols.append("%s:%s:%s" % (host, container, mode))
|
||||
new_vols.append(f"{host}:{container}:{mode}")
|
||||
continue
|
||||
elif len(parts) == 2:
|
||||
if not _is_volume_permissions(parts[1]) and re.match(r'[.~]', parts[0]):
|
||||
host = os.path.abspath(os.path.expanduser(parts[0]))
|
||||
check_collision(parts[1], 'volumes')
|
||||
new_vols.append("%s:%s:rw" % (host, parts[1]))
|
||||
new_vols.append(f"{host}:{parts[1]}:rw")
|
||||
continue
|
||||
check_collision(parts[min(1, len(parts) - 1)], 'volumes')
|
||||
new_vols.append(vol)
|
||||
@@ -664,12 +660,12 @@ def _preprocess_mounts(module, values):
|
||||
if len(parts) == 3:
|
||||
host, container, mode = parts
|
||||
if not _is_volume_permissions(mode):
|
||||
module.fail_json(msg='Found invalid volumes mode: {0}'.format(mode))
|
||||
module.fail_json(msg=f'Found invalid volumes mode: {mode}')
|
||||
elif len(parts) == 2:
|
||||
if not _is_volume_permissions(parts[1]):
|
||||
host, container, mode = (parts + ['rw'])
|
||||
if host is not None:
|
||||
new_binds.append('%s:%s:%s' % (host, container, mode))
|
||||
new_binds.append(f'{host}:{container}:{mode}')
|
||||
values['volume_binds'] = new_binds
|
||||
return values
|
||||
|
||||
@@ -694,12 +690,12 @@ def _preprocess_log(module, values):
|
||||
options = {}
|
||||
for k, v in values['log_options'].items():
|
||||
if not isinstance(v, str):
|
||||
value = to_text(v, errors='surrogate_or_strict')
|
||||
module.warn(
|
||||
"Non-string value found for log_options option '%s'. The value is automatically converted to '%s'. "
|
||||
"If this is not correct, or you want to avoid such warnings, please quote the value." % (
|
||||
k, to_text(v, errors='surrogate_or_strict'))
|
||||
f"Non-string value found for log_options option '{k}'. The value is automatically converted to {value!r}. "
|
||||
"If this is not correct, or you want to avoid such warnings, please quote the value."
|
||||
)
|
||||
v = to_text(v, errors='surrogate_or_strict')
|
||||
v = value
|
||||
options[k] = v
|
||||
result['log_options'] = options
|
||||
return result
|
||||
@@ -735,7 +731,7 @@ def _preprocess_ports(module, values):
|
||||
if not re.match(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$', parts[0]) and not re.match(r'^\[[0-9a-fA-F:]+(?:|%[^\]/]+)\]$', ipaddr):
|
||||
module.fail_json(
|
||||
msg='Bind addresses for published ports must be IPv4 or IPv6 addresses, not hostnames. '
|
||||
'Use the dig lookup to resolve hostnames. (Found hostname: {0})'.format(ipaddr)
|
||||
f'Use the dig lookup to resolve hostnames. (Found hostname: {ipaddr})'
|
||||
)
|
||||
if re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr):
|
||||
ipaddr = ipaddr[1:-1]
|
||||
@@ -748,12 +744,12 @@ def _preprocess_ports(module, values):
|
||||
port_binds = len(container_ports) * [(ipaddr,)]
|
||||
else:
|
||||
module.fail_json(
|
||||
msg='Invalid port description "%s" - expected 1 to 3 colon-separated parts, but got %d. '
|
||||
'Maybe you forgot to use square brackets ([...]) around an IPv6 address?' % (port, p_len)
|
||||
msg=f'Invalid port description "{port}" - expected 1 to 3 colon-separated parts, but got {p_len}. '
|
||||
'Maybe you forgot to use square brackets ([...]) around an IPv6 address?'
|
||||
)
|
||||
|
||||
for bind, container_port in zip(port_binds, container_ports):
|
||||
idx = '{0}/{1}'.format(container_port, protocol) if protocol else container_port
|
||||
idx = f'{container_port}/{protocol}' if protocol else container_port
|
||||
if idx in binds:
|
||||
old_bind = binds[idx]
|
||||
if isinstance(old_bind, list):
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.common.text.converters import to_native, to_text
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.module_utils.common.text.formatters import human_to_bytes
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
@@ -123,7 +123,7 @@ def _get_ansible_type(type):
|
||||
if type == 'set':
|
||||
return 'list'
|
||||
if type not in ('list', 'dict', 'bool', 'int', 'float', 'str'):
|
||||
raise Exception('Invalid type "%s"' % (type, ))
|
||||
raise Exception(f'Invalid type "{type}"')
|
||||
return type
|
||||
|
||||
|
||||
@@ -248,8 +248,9 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
value = normalize_links(value)
|
||||
params[dest_para] = value
|
||||
if parameters:
|
||||
ups = ', '.join([f'"{p}"' for p in sorted(parameters)])
|
||||
raise Exception(
|
||||
'Unknown parameter(s) for connect_container_to_network for Docker API driver: %s' % (', '.join(['"%s"' % p for p in sorted(parameters)])))
|
||||
f'Unknown parameter(s) for connect_container_to_network for Docker API driver: {ups}')
|
||||
ipam_config = {}
|
||||
for param in ('IPv4Address', 'IPv6Address'):
|
||||
if param in params:
|
||||
@@ -307,7 +308,7 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
output = client._get_result_tty(False, res, config['Config']['Tty'])
|
||||
return output, True
|
||||
else:
|
||||
return "Result logged using `%s` driver" % logging_driver, False
|
||||
return f"Result logged using `{logging_driver}` driver", False
|
||||
|
||||
def update_container(self, client, container_id, update_parameters):
|
||||
result = client.post_json_to_json('/containers/{0}/update', container_id, data=update_parameters)
|
||||
@@ -343,13 +344,13 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
# New docker daemon versions do not allow containers to be removed
|
||||
# if they are paused. Make sure we do not end up in an infinite loop.
|
||||
if count == 3:
|
||||
raise Exception('%s [tried to unpause three times]' % to_native(exc))
|
||||
raise Exception(f'{exc} [tried to unpause three times]')
|
||||
count += 1
|
||||
# Unpause
|
||||
try:
|
||||
self.unpause_container(client, container_id)
|
||||
except Exception as exc2:
|
||||
raise Exception('%s [while unpausing]' % to_native(exc2))
|
||||
raise Exception(f'{exc2} [while unpausing]')
|
||||
# Now try again
|
||||
continue
|
||||
raise
|
||||
@@ -369,13 +370,13 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
# New docker daemon versions do not allow containers to be removed
|
||||
# if they are paused. Make sure we do not end up in an infinite loop.
|
||||
if count == 3:
|
||||
raise Exception('%s [tried to unpause three times]' % to_native(exc))
|
||||
raise Exception(f'{exc} [tried to unpause three times]')
|
||||
count += 1
|
||||
# Unpause
|
||||
try:
|
||||
self.unpause_container(client, container_id)
|
||||
except Exception as exc2:
|
||||
raise Exception('%s [while unpausing]' % to_native(exc2))
|
||||
raise Exception(f'{exc2} [while unpausing]')
|
||||
# Now try again
|
||||
continue
|
||||
if 'removal of container ' in exc.explanation and ' is already in progress' in exc.explanation:
|
||||
@@ -389,10 +390,10 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
try:
|
||||
runner()
|
||||
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())
|
||||
|
||||
|
||||
@@ -611,7 +612,7 @@ def _get_default_host_ip(module, client):
|
||||
network = client.get_network(network_data['name'])
|
||||
if network is None:
|
||||
client.fail(
|
||||
"Cannot inspect the network '{0}' to determine the default IP".format(network_data['name']),
|
||||
f"Cannot inspect the network '{network_data['name']}' to determine the default IP",
|
||||
)
|
||||
if network.get('Driver') == 'bridge' and network.get('Options', {}).get('com.docker.network.bridge.host_binding_ipv4'):
|
||||
ip = network['Options']['com.docker.network.bridge.host_binding_ipv4']
|
||||
@@ -658,7 +659,7 @@ def _get_expected_env_value(module, client, api_version, image, value, sentry):
|
||||
expected_env[parts[0]] = parts[1]
|
||||
param_env = []
|
||||
for key, env_value in expected_env.items():
|
||||
param_env.append("%s=%s" % (key, env_value))
|
||||
param_env.append(f"{key}={env_value}")
|
||||
return param_env
|
||||
|
||||
|
||||
@@ -744,7 +745,7 @@ def _preprocess_etc_hosts(module, client, api_version, value):
|
||||
return value
|
||||
results = []
|
||||
for key, value in value.items():
|
||||
results.append('%s%s%s' % (key, ':', value))
|
||||
results.append(f'{key}:{value}')
|
||||
return results
|
||||
|
||||
|
||||
@@ -783,7 +784,7 @@ def _preprocess_convert_to_bytes(module, values, name, unlimited_value=None):
|
||||
values[name] = value
|
||||
return values
|
||||
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 _get_image_labels(image):
|
||||
@@ -815,7 +816,7 @@ def _preprocess_links(module, client, api_version, value):
|
||||
link, alias = parsed_link
|
||||
else:
|
||||
link, alias = parsed_link[0], parsed_link[0]
|
||||
result.append('/%s:/%s/%s' % (link, module.params['name'], alias))
|
||||
result.append(f"/{link}:/{module.params['name']}/{alias}")
|
||||
|
||||
return result
|
||||
|
||||
@@ -830,11 +831,12 @@ def _ignore_mismatching_label_result(module, client, api_version, option, image,
|
||||
for label in image_labels:
|
||||
if label not in labels_param:
|
||||
# Format label for error message
|
||||
would_remove_labels.append('"%s"' % (label, ))
|
||||
would_remove_labels.append(f'"{label}"')
|
||||
if would_remove_labels:
|
||||
labels = ', '.join(would_remove_labels)
|
||||
msg = ("Some labels should be removed but are present in the base image. You can set image_label_mismatch to 'ignore' to ignore"
|
||||
" this error. Labels: {0}")
|
||||
client.fail(msg.format(', '.join(would_remove_labels)))
|
||||
f" this error. Labels: {labels}")
|
||||
client.fail(msg)
|
||||
return False
|
||||
|
||||
|
||||
@@ -860,7 +862,7 @@ def _preprocess_network_values(module, client, api_version, options, values):
|
||||
for network in values['networks']:
|
||||
network['id'] = _get_network_id(module, client, network['name'])
|
||||
if not network['id']:
|
||||
client.fail("Parameter error: network named %s could not be found. Does it exist?" % (network['name'], ))
|
||||
client.fail(f"Parameter error: network named {network['name']} could not be found. Does it exist?")
|
||||
|
||||
if 'network_mode' in values:
|
||||
values['network_mode'] = _preprocess_container_names(module, client, api_version, values['network_mode'])
|
||||
@@ -878,7 +880,7 @@ def _get_network_id(module, client, network_name):
|
||||
break
|
||||
return network_id
|
||||
except Exception as exc:
|
||||
client.fail("Error getting network id for %s - %s" % (network_name, to_native(exc)))
|
||||
client.fail(f"Error getting network id for {network_name} - {exc}")
|
||||
|
||||
|
||||
def _get_values_network(module, container, api_version, options, image, host_info):
|
||||
@@ -947,7 +949,7 @@ def _get_bind_from_dict(volume_dict):
|
||||
if isinstance(config, dict) and config.get('bind'):
|
||||
container_path = config.get('bind')
|
||||
mode = config.get('mode', 'rw')
|
||||
results.append("%s:%s:%s" % (host_path, container_path, mode))
|
||||
results.append(f"{host_path}:{container_path}:{mode}")
|
||||
return results
|
||||
|
||||
|
||||
@@ -1133,7 +1135,7 @@ def _get_expected_values_platform(module, client, api_version, options, image, v
|
||||
daemon_arch=host_info.get('Architecture') if host_info else None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
module.fail_json(msg='Error while parsing platform parameer: %s' % (to_native(exc), ))
|
||||
module.fail_json(msg=f'Error while parsing platform parameer: {exc}')
|
||||
return expected_values
|
||||
|
||||
|
||||
@@ -1203,7 +1205,7 @@ def _get_expected_values_ports(module, client, api_version, options, image, valu
|
||||
expected_bound_ports = {}
|
||||
for container_port, config in values['published_ports'].items():
|
||||
if isinstance(container_port, int):
|
||||
container_port = "%s/tcp" % container_port
|
||||
container_port = f"{container_port}/tcp"
|
||||
if len(config) == 1:
|
||||
if isinstance(config[0], int):
|
||||
expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': config[0]}]
|
||||
@@ -1243,7 +1245,7 @@ def _set_values_ports(module, data, api_version, options, values):
|
||||
if len(port_definition) == 2:
|
||||
proto = port_definition[1]
|
||||
port = port_definition[0]
|
||||
exposed_ports['%s/%s' % (port, proto)] = {}
|
||||
exposed_ports[f'{port}/{proto}'] = {}
|
||||
data['ExposedPorts'] = exposed_ports
|
||||
if 'published_ports' in values:
|
||||
if 'HostConfig' not in data:
|
||||
@@ -1282,9 +1284,9 @@ def _preprocess_container_names(module, client, api_version, value):
|
||||
if container is None:
|
||||
# If we cannot find the container, issue a warning and continue with
|
||||
# what the user specified.
|
||||
module.warn('Cannot find a container with name or ID "{0}"'.format(container_name))
|
||||
module.warn(f'Cannot find a container with name or ID "{container_name}"')
|
||||
return value
|
||||
return 'container:{0}'.format(container['Id'])
|
||||
return f"container:{container['Id']}"
|
||||
|
||||
|
||||
def _get_value_command(module, container, api_version, options, image, host_info):
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
import re
|
||||
from time import sleep
|
||||
|
||||
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.util import (
|
||||
DifferenceTracker,
|
||||
@@ -102,11 +102,11 @@ class ContainerManager(DockerBaseClass):
|
||||
if re.match(r'^\[[0-9a-fA-F:]+\]$', self.param_default_host_ip):
|
||||
valid_ip = True
|
||||
if re.match(r'^[0-9a-fA-F:]+$', self.param_default_host_ip):
|
||||
self.param_default_host_ip = '[{0}]'.format(self.param_default_host_ip)
|
||||
self.param_default_host_ip = f'[{self.param_default_host_ip}]'
|
||||
valid_ip = True
|
||||
if not valid_ip:
|
||||
self.fail('The value of default_host_ip must be an empty string, an IPv4 address, '
|
||||
'or an IPv6 address. Got "{0}" instead.'.format(self.param_default_host_ip))
|
||||
f'or an IPv6 address. Got "{self.param_default_host_ip}" instead.')
|
||||
|
||||
def _collect_all_options(self, active_options):
|
||||
all_options = {}
|
||||
@@ -157,23 +157,23 @@ class ContainerManager(DockerBaseClass):
|
||||
key_main = comp_aliases.get(key)
|
||||
if key_main is None:
|
||||
if key_main in all_module_options:
|
||||
self.fail("The module option '%s' cannot be specified in the comparisons dict, "
|
||||
"since it does not correspond to container's state!" % key)
|
||||
self.fail(f"The module option '{key}' cannot be specified in the comparisons dict, "
|
||||
"since it does not correspond to container's state!")
|
||||
if key not in self.all_options or self.all_options[key].not_an_ansible_option:
|
||||
self.fail("Unknown module option '%s' in comparisons dict!" % key)
|
||||
self.fail(f"Unknown module option '{key}' in comparisons dict!")
|
||||
key_main = key
|
||||
if key_main in comp_aliases_used:
|
||||
self.fail("Both '%s' and '%s' (aliases of %s) are specified in comparisons dict!" % (key, comp_aliases_used[key_main], key_main))
|
||||
self.fail(f"Both '{key}' and '{comp_aliases_used[key_main]}' (aliases of {key_main}) are specified in comparisons dict!")
|
||||
comp_aliases_used[key_main] = key
|
||||
# Check value and update accordingly
|
||||
if value in ('strict', 'ignore'):
|
||||
self.all_options[key_main].comparison = value
|
||||
elif value == 'allow_more_present':
|
||||
if self.all_options[key_main].comparison_type == 'value':
|
||||
self.fail("Option '%s' is a value and not a set/list/dict, so its comparison cannot be %s" % (key, value))
|
||||
self.fail(f"Option '{key}' is a value and not a set/list/dict, so its comparison cannot be {value}")
|
||||
self.all_options[key_main].comparison = value
|
||||
else:
|
||||
self.fail("Unknown comparison mode '%s'!" % value)
|
||||
self.fail(f"Unknown comparison mode '{value}'!")
|
||||
# Copy values
|
||||
for option in self.all_options.values():
|
||||
if option.copy_comparison_from is not None:
|
||||
@@ -228,8 +228,8 @@ class ContainerManager(DockerBaseClass):
|
||||
if result is None:
|
||||
if accept_removal:
|
||||
return result
|
||||
msg = 'Encontered vanished container while waiting for container "{0}"'
|
||||
self.fail(msg.format(container_id))
|
||||
msg = f'Encontered vanished container while waiting for container "{container_id}"'
|
||||
self.fail(msg)
|
||||
# Check container state
|
||||
state_info = result.get('State') or {}
|
||||
if health_state:
|
||||
@@ -238,13 +238,13 @@ class ContainerManager(DockerBaseClass):
|
||||
if complete_states is not None and state in complete_states:
|
||||
return result
|
||||
if wait_states is not None and state not in wait_states:
|
||||
msg = 'Encontered unexpected state "{1}" while waiting for container "{0}"'
|
||||
self.fail(msg.format(container_id, state), container=result)
|
||||
msg = f'Encontered unexpected state "{state}" while waiting for container "{container_id}"'
|
||||
self.fail(msg, container=result)
|
||||
# Wait
|
||||
if max_wait is not None:
|
||||
if total_wait > max_wait or delay < 1E-4:
|
||||
msg = 'Timeout of {1} seconds exceeded while waiting for container "{0}"'
|
||||
self.fail(msg.format(container_id, max_wait), container=result)
|
||||
msg = f'Timeout of {max_wait} seconds exceeded while waiting for container "{container_id}"'
|
||||
self.fail(msg, container=result)
|
||||
if total_wait + delay > max_wait:
|
||||
delay = max_wait - total_wait
|
||||
sleep(delay)
|
||||
@@ -373,9 +373,7 @@ class ContainerManager(DockerBaseClass):
|
||||
else:
|
||||
self.engine_driver.unpause_container(self.client, container.id)
|
||||
except Exception as exc:
|
||||
self.fail("Error %s container %s: %s" % (
|
||||
"pausing" if self.param_paused else "unpausing", container.id, to_native(exc)
|
||||
))
|
||||
self.fail(f"Error {'pausing' if self.param_paused else 'unpausing'} container {container.id}: {exc}")
|
||||
container = self._get_container(container.id)
|
||||
self.results['changed'] = True
|
||||
self.results['actions'].append(dict(set_paused=self.param_paused))
|
||||
@@ -440,14 +438,14 @@ class ContainerManager(DockerBaseClass):
|
||||
if is_image_name_id(image_parameter):
|
||||
image = self.engine_driver.inspect_image_by_id(self.client, image_parameter)
|
||||
if image is None:
|
||||
self.client.fail("Cannot find image with ID %s" % (image_parameter, ))
|
||||
self.client.fail(f"Cannot find image with ID {image_parameter}")
|
||||
else:
|
||||
repository, tag = parse_repository_tag(image_parameter)
|
||||
if not tag:
|
||||
tag = "latest"
|
||||
image = self.engine_driver.inspect_image_by_name(self.client, repository, tag)
|
||||
if not image and self.param_pull == "never":
|
||||
self.client.fail("Cannot find image with name %s:%s, and pull=never" % (repository, tag))
|
||||
self.client.fail(f"Cannot find image with name {repository}:{tag}, and pull=never")
|
||||
if not image or self.param_pull == "always":
|
||||
if not self.check_mode:
|
||||
self.log("Pull the image.")
|
||||
@@ -455,16 +453,16 @@ class ContainerManager(DockerBaseClass):
|
||||
self.client, repository, tag, platform=self.module.params['platform'])
|
||||
if alreadyToLatest:
|
||||
self.results['changed'] = False
|
||||
self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag), changed=False))
|
||||
self.results['actions'].append(dict(pulled_image=f"{repository}:{tag}", changed=False))
|
||||
else:
|
||||
self.results['changed'] = True
|
||||
self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag), changed=True))
|
||||
self.results['actions'].append(dict(pulled_image=f"{repository}:{tag}", changed=True))
|
||||
elif not image or self.param_pull_check_mode_behavior == 'always':
|
||||
# If the image is not there, or pull_check_mode_behavior == 'always', claim we'll
|
||||
# pull. (Implicitly: if the image is there, claim it already was latest unless
|
||||
# pull_check_mode_behavior == 'always'.)
|
||||
self.results['changed'] = True
|
||||
action = dict(pulled_image="%s:%s" % (repository, tag))
|
||||
action = dict(pulled_image=f"{repository}:{tag}")
|
||||
if not image:
|
||||
action['changed'] = True
|
||||
self.results['actions'].append(action)
|
||||
@@ -620,7 +618,7 @@ class ContainerManager(DockerBaseClass):
|
||||
if network.get('links'):
|
||||
expected_links = []
|
||||
for link, alias in network['links']:
|
||||
expected_links.append("%s:%s" % (link, alias))
|
||||
expected_links.append(f"{link}:{alias}")
|
||||
if not compare_generic(expected_links, network_info.get('Links'), 'allow_more_present', 'set'):
|
||||
diff = True
|
||||
if network.get('mac_address') and network['mac_address'] != network_info.get('MacAddress'):
|
||||
@@ -674,7 +672,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.diff['differences'] = [dict(network_differences=network_differences)]
|
||||
for netdiff in network_differences:
|
||||
self.diff_tracker.add(
|
||||
'network.{0}'.format(netdiff['parameter']['name']),
|
||||
f"network.{netdiff['parameter']['name']}",
|
||||
parameter=netdiff['parameter'],
|
||||
active=netdiff['container']
|
||||
)
|
||||
@@ -691,7 +689,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.diff['differences'] = [dict(purge_networks=extra_networks)]
|
||||
for extra_network in extra_networks:
|
||||
self.diff_tracker.add(
|
||||
'network.{0}'.format(extra_network['name']),
|
||||
f"network.{extra_network['name']}",
|
||||
active=extra_network
|
||||
)
|
||||
self.results['changed'] = True
|
||||
@@ -707,18 +705,17 @@ class ContainerManager(DockerBaseClass):
|
||||
try:
|
||||
self.engine_driver.disconnect_container_from_network(self.client, container.id, diff['parameter']['id'])
|
||||
except Exception as exc:
|
||||
self.fail("Error disconnecting container from network %s - %s" % (diff['parameter']['name'],
|
||||
to_native(exc)))
|
||||
self.fail(f"Error disconnecting container from network {diff['parameter']['name']} - {exc}")
|
||||
# connect to the network
|
||||
self.results['actions'].append(dict(added_to_network=diff['parameter']['name'], network_parameters=diff['parameter']))
|
||||
if not self.check_mode:
|
||||
params = {key: value for key, value in diff['parameter'].items() if key not in ('id', 'name')}
|
||||
try:
|
||||
self.log("Connecting container to network %s" % diff['parameter']['id'])
|
||||
self.log(f"Connecting container to network {diff['parameter']['id']}")
|
||||
self.log(params, pretty_print=True)
|
||||
self.engine_driver.connect_container_to_network(self.client, container.id, diff['parameter']['id'], params)
|
||||
except Exception as exc:
|
||||
self.fail("Error connecting container to network %s - %s" % (diff['parameter']['name'], to_native(exc)))
|
||||
self.fail(f"Error connecting container to network {diff['parameter']['name']} - {exc}")
|
||||
return self._get_container(container.id)
|
||||
|
||||
def _purge_networks(self, container, networks):
|
||||
@@ -728,14 +725,13 @@ class ContainerManager(DockerBaseClass):
|
||||
try:
|
||||
self.engine_driver.disconnect_container_from_network(self.client, container.id, network['name'])
|
||||
except Exception as exc:
|
||||
self.fail("Error disconnecting container from network %s - %s" % (network['name'],
|
||||
to_native(exc)))
|
||||
self.fail(f"Error disconnecting container from network {network['name']} - {exc}")
|
||||
return self._get_container(container.id)
|
||||
|
||||
def container_create(self, image):
|
||||
create_parameters = self._compose_create_parameters(image)
|
||||
self.log("create container")
|
||||
self.log("image: %s parameters:" % image)
|
||||
self.log(f"image: {image} parameters:")
|
||||
self.log(create_parameters, pretty_print=True)
|
||||
networks = {}
|
||||
if self.param_networks_cli_compatible and self.module.params['networks']:
|
||||
@@ -754,19 +750,19 @@ class ContainerManager(DockerBaseClass):
|
||||
try:
|
||||
container_id = self.engine_driver.create_container(self.client, self.param_name, create_parameters, networks=networks)
|
||||
except Exception as exc:
|
||||
self.fail("Error creating container: %s" % to_native(exc))
|
||||
self.fail(f"Error creating container: {exc}")
|
||||
return self._get_container(container_id)
|
||||
return new_container
|
||||
|
||||
def container_start(self, container_id):
|
||||
self.log("start container %s" % (container_id))
|
||||
self.log(f"start container {container_id}")
|
||||
self.results['actions'].append(dict(started=container_id))
|
||||
self.results['changed'] = True
|
||||
if not self.check_mode:
|
||||
try:
|
||||
self.engine_driver.start_container(self.client, container_id)
|
||||
except Exception as exc:
|
||||
self.fail("Error starting container %s: %s" % (container_id, to_native(exc)))
|
||||
self.fail(f"Error starting container {container_id}: {exc}")
|
||||
|
||||
if self.module.params['detach'] is False:
|
||||
status = self.engine_driver.wait_for_container(self.client, container_id)
|
||||
@@ -798,18 +794,18 @@ class ContainerManager(DockerBaseClass):
|
||||
|
||||
def container_remove(self, container_id, link=False, force=False):
|
||||
volume_state = (not self.param_keep_volumes)
|
||||
self.log("remove container container:%s v:%s link:%s force%s" % (container_id, volume_state, link, force))
|
||||
self.log(f"remove container container:{container_id} v:{volume_state} link:{link} force{force}")
|
||||
self.results['actions'].append(dict(removed=container_id, volume_state=volume_state, link=link, force=force))
|
||||
self.results['changed'] = True
|
||||
if not self.check_mode:
|
||||
try:
|
||||
self.engine_driver.remove_container(self.client, container_id, remove_volumes=volume_state, link=link, force=force)
|
||||
except Exception as exc:
|
||||
self.client.fail("Error removing container %s: %s" % (container_id, to_native(exc)))
|
||||
self.client.fail(f"Error removing container {container_id}: {exc}")
|
||||
|
||||
def container_update(self, container_id, update_parameters):
|
||||
if update_parameters:
|
||||
self.log("update container %s" % (container_id))
|
||||
self.log(f"update container {container_id}")
|
||||
self.log(update_parameters, pretty_print=True)
|
||||
self.results['actions'].append(dict(updated=container_id, update_parameters=update_parameters))
|
||||
self.results['changed'] = True
|
||||
@@ -817,7 +813,7 @@ class ContainerManager(DockerBaseClass):
|
||||
try:
|
||||
self.engine_driver.update_container(self.client, container_id, update_parameters)
|
||||
except Exception as exc:
|
||||
self.fail("Error updating container %s: %s" % (container_id, to_native(exc)))
|
||||
self.fail(f"Error updating container {container_id}: {exc}")
|
||||
return self._get_container(container_id)
|
||||
|
||||
def container_kill(self, container_id):
|
||||
@@ -827,7 +823,7 @@ class ContainerManager(DockerBaseClass):
|
||||
try:
|
||||
self.engine_driver.kill_container(self.client, container_id, kill_signal=self.param_kill_signal)
|
||||
except Exception as exc:
|
||||
self.fail("Error killing container %s: %s" % (container_id, to_native(exc)))
|
||||
self.fail(f"Error killing container {container_id}: {exc}")
|
||||
|
||||
def container_restart(self, container_id):
|
||||
self.results['actions'].append(dict(restarted=container_id, timeout=self.module.params['stop_timeout']))
|
||||
@@ -836,7 +832,7 @@ class ContainerManager(DockerBaseClass):
|
||||
try:
|
||||
self.engine_driver.restart_container(self.client, container_id, self.module.params['stop_timeout'] or 10)
|
||||
except Exception as exc:
|
||||
self.fail("Error restarting container %s: %s" % (container_id, to_native(exc)))
|
||||
self.fail(f"Error restarting container {container_id}: {exc}")
|
||||
return self._get_container(container_id)
|
||||
|
||||
def container_stop(self, container_id):
|
||||
@@ -849,7 +845,7 @@ class ContainerManager(DockerBaseClass):
|
||||
try:
|
||||
self.engine_driver.stop_container(self.client, container_id, self.module.params['stop_timeout'])
|
||||
except Exception as exc:
|
||||
self.fail("Error stopping container %s: %s" % (container_id, to_native(exc)))
|
||||
self.fail(f"Error stopping container {container_id}: {exc}")
|
||||
|
||||
|
||||
def run_module(engine_driver):
|
||||
|
||||
Reference in New Issue
Block a user