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:
@@ -172,7 +172,6 @@ filters:
|
||||
import re
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
|
||||
|
||||
from ansible_collections.community.docker.plugins.module_utils.common_api import (
|
||||
@@ -198,7 +197,8 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
|
||||
NAME = 'community.docker.docker_containers'
|
||||
|
||||
def _slugify(self, value):
|
||||
return 'docker_%s' % (re.sub(r'[^\w-]', '_', value).lower().lstrip('_'))
|
||||
slug = re.sub(r'[^\w-]', '_', value).lower().lstrip('_')
|
||||
return f'docker_{slug}'
|
||||
|
||||
def _populate(self, client):
|
||||
strict = self.get_option('strict')
|
||||
@@ -221,7 +221,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
|
||||
}
|
||||
containers = client.get_json('/containers/json', params=params)
|
||||
except APIError as exc:
|
||||
raise AnsibleError("Error listing containers: %s" % to_native(exc))
|
||||
raise AnsibleError(f"Error listing containers: {exc}")
|
||||
|
||||
if add_legacy_groups:
|
||||
self.inventory.add_group('running')
|
||||
@@ -255,7 +255,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
|
||||
try:
|
||||
inspect = client.get_json('/containers/{0}/json', id)
|
||||
except APIError as exc:
|
||||
raise AnsibleError("Error inspecting container %s - %s" % (name, str(exc)))
|
||||
raise AnsibleError(f"Error inspecting container {name} - {exc}")
|
||||
|
||||
state = inspect.get('State') or dict()
|
||||
config = inspect.get('Config') or dict()
|
||||
@@ -268,19 +268,19 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
|
||||
# Add container to groups
|
||||
image_name = config.get('Image')
|
||||
if image_name and add_legacy_groups:
|
||||
groups.append('image_{0}'.format(image_name))
|
||||
groups.append(f'image_{image_name}')
|
||||
|
||||
stack_name = labels.get('com.docker.stack.namespace')
|
||||
if stack_name:
|
||||
full_facts['docker_stack'] = stack_name
|
||||
if add_legacy_groups:
|
||||
groups.append('stack_{0}'.format(stack_name))
|
||||
groups.append(f'stack_{stack_name}')
|
||||
|
||||
service_name = labels.get('com.docker.swarm.service.name')
|
||||
if service_name:
|
||||
full_facts['docker_service'] = service_name
|
||||
if add_legacy_groups:
|
||||
groups.append('service_{0}'.format(service_name))
|
||||
groups.append(f'service_{service_name}')
|
||||
|
||||
ansible_connection = None
|
||||
if connection_type == 'ssh':
|
||||
@@ -289,7 +289,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
|
||||
# Lookup the public facing port Nat'ed to ssh port.
|
||||
network_settings = inspect.get('NetworkSettings') or {}
|
||||
port_settings = network_settings.get('Ports') or {}
|
||||
port = port_settings.get('%d/tcp' % (ssh_port, ))[0]
|
||||
port = port_settings.get(f'{ssh_port}/tcp')[0]
|
||||
except (IndexError, AttributeError, TypeError):
|
||||
port = dict()
|
||||
|
||||
@@ -383,9 +383,9 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
|
||||
self._populate(client)
|
||||
except DockerException as e:
|
||||
raise AnsibleError(
|
||||
'An unexpected Docker error occurred: {0}'.format(e)
|
||||
f'An unexpected Docker error occurred: {e}'
|
||||
)
|
||||
except RequestException as e:
|
||||
raise AnsibleError(
|
||||
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(e)
|
||||
f'An unexpected requests error occurred when trying to talk to the Docker daemon: {e}'
|
||||
)
|
||||
|
||||
@@ -131,11 +131,11 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
|
||||
|
||||
command = [self.DOCKER_MACHINE_PATH]
|
||||
command.extend(args)
|
||||
display.debug('Executing command {0}'.format(command))
|
||||
display.debug(f'Executing command {command}')
|
||||
try:
|
||||
result = subprocess.check_output(command)
|
||||
except subprocess.CalledProcessError as e:
|
||||
display.warning('Exception {0} caught while executing command {1}, this was the original exception: {2}'.format(type(e).__name__, command, e))
|
||||
display.warning(f'Exception {type(e).__name__} caught while executing command {command}, this was the original exception: {e}')
|
||||
raise e
|
||||
|
||||
return to_text(result).strip()
|
||||
@@ -203,14 +203,14 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
|
||||
|
||||
def _should_skip_host(self, machine_name, env_var_tuples, daemon_env):
|
||||
if not env_var_tuples:
|
||||
warning_prefix = 'Unable to fetch Docker daemon env vars from Docker Machine for host {0}'.format(machine_name)
|
||||
warning_prefix = f'Unable to fetch Docker daemon env vars from Docker Machine for host {machine_name}'
|
||||
if daemon_env in ('require', 'require-silently'):
|
||||
if daemon_env == 'require':
|
||||
display.warning('{0}: host will be skipped'.format(warning_prefix))
|
||||
display.warning(f'{warning_prefix}: host will be skipped')
|
||||
return True
|
||||
else: # 'optional', 'optional-silently'
|
||||
if daemon_env == 'optional':
|
||||
display.warning('{0}: host will lack dm_DOCKER_xxx variables'.format(warning_prefix))
|
||||
display.warning(f'{warning_prefix}: host will lack dm_DOCKER_xxx variables')
|
||||
return False
|
||||
|
||||
def _populate(self):
|
||||
@@ -261,7 +261,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
|
||||
|
||||
# set variables based on Docker Machine env variables
|
||||
for kv in env_var_tuples:
|
||||
self.inventory.set_variable(machine_name, 'dm_{0}'.format(kv[0]), make_unsafe(kv[1]))
|
||||
self.inventory.set_variable(machine_name, f'dm_{kv[0]}', make_unsafe(kv[1]))
|
||||
|
||||
if self.get_option('verbose_output'):
|
||||
self.inventory.set_variable(machine_name, 'docker_machine_node_attributes', unsafe_node_attrs)
|
||||
@@ -279,8 +279,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
|
||||
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), unsafe_node_attrs, machine_name, strict=strict)
|
||||
|
||||
except Exception as e:
|
||||
raise AnsibleError('Unable to fetch hosts from Docker Machine, this was the original exception: %s' %
|
||||
to_native(e), orig_exc=e)
|
||||
raise AnsibleError(f'Unable to fetch hosts from Docker Machine, this was the original exception: {e}') from e
|
||||
|
||||
def verify_file(self, path):
|
||||
"""Return the possibility of a file being consumable by this plugin."""
|
||||
|
||||
@@ -149,7 +149,6 @@ keyed_groups:
|
||||
'''
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
from ansible_collections.community.docker.plugins.module_utils.common import get_connect_params
|
||||
from ansible_collections.community.docker.plugins.module_utils.util import update_tls_hostname
|
||||
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
|
||||
@@ -255,8 +254,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
|
||||
unsafe_node_attrs['ID'],
|
||||
strict=strict)
|
||||
except Exception as e:
|
||||
raise AnsibleError('Unable to fetch hosts from Docker swarm API, this was the original exception: %s' %
|
||||
to_native(e))
|
||||
raise AnsibleError(f'Unable to fetch hosts from Docker swarm API, this was the original exception: {e}')
|
||||
|
||||
def verify_file(self, path):
|
||||
"""Return the possibly of a file being consumable by this plugin."""
|
||||
|
||||
Reference in New Issue
Block a user