Skip to content

Commit

Permalink
connection plugins: use f-strings (#9322)
Browse files Browse the repository at this point in the history
* connection plugins: use f-strings

* add changelog frag

(cherry picked from commit d539b00)
  • Loading branch information
russoz authored and patchback[bot] committed Dec 24, 2024
1 parent e3f72bc commit 6277b0b
Show file tree
Hide file tree
Showing 11 changed files with 105 additions and 99 deletions.
11 changes: 11 additions & 0 deletions changelogs/fragments/9322-fstr-connection-plugins.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
minor_changes:
- chroot connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- funcd connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- incus connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- iocage connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- jail connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- lxc connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- lxd connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- qubes connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- saltstack connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
- zone connection plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9322).
24 changes: 12 additions & 12 deletions plugins/connection/chroot.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,15 +120,15 @@ def __init__(self, play_context, new_stdin, *args, **kwargs):

# do some trivial checks for ensuring 'host' is actually a chroot'able dir
if not os.path.isdir(self.chroot):
raise AnsibleError("%s is not a directory" % self.chroot)
raise AnsibleError(f"{self.chroot} is not a directory")

chrootsh = os.path.join(self.chroot, 'bin/sh')
# Want to check for a usable bourne shell inside the chroot.
# is_executable() == True is sufficient. For symlinks it
# gets really complicated really fast. So we punt on finding that
# out. As long as it's a symlink we assume that it will work
if not (is_executable(chrootsh) or (os.path.lexists(chrootsh) and os.path.islink(chrootsh))):
raise AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot)
raise AnsibleError(f"{self.chroot} does not look like a chrootable dir (/bin/sh missing)")

def _connect(self):
""" connect to the chroot """
Expand Down Expand Up @@ -161,7 +161,7 @@ def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
executable = self.get_option('executable')
local_cmd = [self.chroot_cmd, self.chroot, executable, '-c', cmd]

display.vvv("EXEC %s" % local_cmd, host=self.chroot)
display.vvv(f"EXEC {local_cmd}", host=self.chroot)
local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Expand Down Expand Up @@ -195,7 +195,7 @@ def _prefix_login_path(remote_path):
def put_file(self, in_path, out_path):
""" transfer a file from local to chroot """
super(Connection, self).put_file(in_path, out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
display.vvv(f"PUT {in_path} TO {out_path}", host=self.chroot)

out_path = shlex_quote(self._prefix_login_path(out_path))
try:
Expand All @@ -205,27 +205,27 @@ def put_file(self, in_path, out_path):
else:
count = ''
try:
p = self._buffered_exec_command('dd of=%s bs=%s%s' % (out_path, BUFSIZE, count), stdin=in_file)
p = self._buffered_exec_command(f'dd of={out_path} bs={BUFSIZE}{count}', stdin=in_file)
except OSError:
raise AnsibleError("chroot connection requires dd command in the chroot")
try:
stdout, stderr = p.communicate()
except Exception:
traceback.print_exc()
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}")
if p.returncode != 0:
raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")
except IOError:
raise AnsibleError("file or module does not exist at: %s" % in_path)
raise AnsibleError(f"file or module does not exist at: {in_path}")

def fetch_file(self, in_path, out_path):
""" fetch a file from chroot to local """
super(Connection, self).fetch_file(in_path, out_path)
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot)
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.chroot)

in_path = shlex_quote(self._prefix_login_path(in_path))
try:
p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE))
p = self._buffered_exec_command(f'dd if={in_path} bs={BUFSIZE}')
except OSError:
raise AnsibleError("chroot connection requires dd command in the chroot")

Expand All @@ -237,10 +237,10 @@ def fetch_file(self, in_path, out_path):
chunk = p.stdout.read(BUFSIZE)
except Exception:
traceback.print_exc()
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}")
stdout, stderr = p.communicate()
if p.returncode != 0:
raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}")

def close(self):
""" terminate the connection; nothing to do here """
Expand Down
6 changes: 3 additions & 3 deletions plugins/connection/funcd.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def exec_command(self, cmd, in_data=None, sudoable=True):
raise AnsibleError("Internal Error: this module does not support optimized module pipelining")

# totally ignores privilege escalation
display.vvv("EXEC %s" % cmd, host=self.host)
display.vvv(f"EXEC {cmd}", host=self.host)
p = self.client.command.run(cmd)[self.host]
return p[0], p[1], p[2]

Expand All @@ -87,14 +87,14 @@ def put_file(self, in_path, out_path):
""" transfer a file from local to remote """

out_path = self._normalize_path(out_path, '/')
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
display.vvv(f"PUT {in_path} TO {out_path}", host=self.host)
self.client.local.copyfile.send(in_path, out_path)

def fetch_file(self, in_path, out_path):
""" fetch a file from remote to local """

in_path = self._normalize_path(in_path, '/')
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.host)
# need to use a tmp dir due to difference of semantic for getfile
# ( who take a # directory as destination) and fetch_file, who
# take a file directly
Expand Down
24 changes: 9 additions & 15 deletions plugins/connection/incus.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,14 @@ def exec_command(self, cmd, in_data=None, sudoable=True):
""" execute a command on the Incus host """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)

self._display.vvv(u"EXEC {0}".format(cmd),
self._display.vvv(f"EXEC {cmd}",
host=self._instance())

local_cmd = [
self._incus_cmd,
"--project", self.get_option("project"),
"exec",
"%s:%s" % (self.get_option("remote"), self._instance()),
f"{self.get_option('remote')}:{self._instance()}",
"--",
self._play_context.executable, "-c", cmd]

Expand All @@ -114,33 +114,29 @@ def exec_command(self, cmd, in_data=None, sudoable=True):
stderr = to_text(stderr)

if stderr == "Error: Instance is not running.\n":
raise AnsibleConnectionFailure("instance not running: %s" %
self._instance())
raise AnsibleConnectionFailure(f"instance not running: {self._instance()}")

if stderr == "Error: Instance not found\n":
raise AnsibleConnectionFailure("instance not found: %s" %
self._instance())
raise AnsibleConnectionFailure(f"instance not found: {self._instance()}")

return process.returncode, stdout, stderr

def put_file(self, in_path, out_path):
""" put a file from local to Incus """
super(Connection, self).put_file(in_path, out_path)

self._display.vvv(u"PUT {0} TO {1}".format(in_path, out_path),
self._display.vvv(f"PUT {in_path} TO {out_path}",
host=self._instance())

if not os.path.isfile(to_bytes(in_path, errors='surrogate_or_strict')):
raise AnsibleFileNotFound("input path is not a file: %s" % in_path)
raise AnsibleFileNotFound(f"input path is not a file: {in_path}")

local_cmd = [
self._incus_cmd,
"--project", self.get_option("project"),
"file", "push", "--quiet",
in_path,
"%s:%s/%s" % (self.get_option("remote"),
self._instance(),
out_path)]
f"{self.get_option('remote')}:{self._instance()}/{out_path}"]

local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]

Expand All @@ -150,16 +146,14 @@ def fetch_file(self, in_path, out_path):
""" fetch a file from Incus to local """
super(Connection, self).fetch_file(in_path, out_path)

self._display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path),
self._display.vvv(f"FETCH {in_path} TO {out_path}",
host=self._instance())

local_cmd = [
self._incus_cmd,
"--project", self.get_option("project"),
"file", "pull", "--quiet",
"%s:%s/%s" % (self.get_option("remote"),
self._instance(),
in_path),
f"{self.get_option('remote')}:{self._instance()}/{in_path}",
out_path]

local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
Expand Down
11 changes: 6 additions & 5 deletions plugins/connection/iocage.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,12 @@ def __init__(self, play_context, new_stdin, *args, **kwargs):

jail_uuid = self.get_jail_uuid()

kwargs[Jail.modified_jailname_key] = 'ioc-{0}'.format(jail_uuid)
kwargs[Jail.modified_jailname_key] = f'ioc-{jail_uuid}'

display.vvv(u"Jail {iocjail} has been translated to {rawjail}".format(
iocjail=self.ioc_jail, rawjail=kwargs[Jail.modified_jailname_key]),
host=kwargs[Jail.modified_jailname_key])
display.vvv(
f"Jail {self.ioc_jail} has been translated to {kwargs[Jail.modified_jailname_key]}",
host=kwargs[Jail.modified_jailname_key]
)

super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)

Expand All @@ -81,6 +82,6 @@ def get_jail_uuid(self):
p.wait()

if p.returncode != 0:
raise AnsibleError(u"iocage returned an error: {0}".format(stdout))
raise AnsibleError(f"iocage returned an error: {stdout}")

return stdout.strip('\n')
28 changes: 14 additions & 14 deletions plugins/connection/jail.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,14 @@ def __init__(self, play_context, new_stdin, *args, **kwargs):
self.jexec_cmd = self._search_executable('jexec')

if self.jail not in self.list_jails():
raise AnsibleError("incorrect jail name %s" % self.jail)
raise AnsibleError(f"incorrect jail name {self.jail}")

@staticmethod
def _search_executable(executable):
try:
return get_bin_path(executable)
except ValueError:
raise AnsibleError("%s command not found in PATH" % executable)
raise AnsibleError(f"{executable} command not found in PATH")

def list_jails(self):
p = subprocess.Popen([self.jls_cmd, '-q', 'name'],
Expand All @@ -97,7 +97,7 @@ def _connect(self):
""" connect to the jail; nothing to do here """
super(Connection, self)._connect()
if not self._connected:
display.vvv(u"ESTABLISH JAIL CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self.jail)
display.vvv(f"ESTABLISH JAIL CONNECTION FOR USER: {self._play_context.remote_user}", host=self.jail)
self._connected = True

def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
Expand All @@ -115,11 +115,11 @@ def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
if self._play_context.remote_user is not None:
local_cmd += ['-U', self._play_context.remote_user]
# update HOME since -U does not update the jail environment
set_env = 'HOME=~' + self._play_context.remote_user + ' '
set_env = f"HOME=~{self._play_context.remote_user} "

local_cmd += [self.jail, self._play_context.executable, '-c', set_env + cmd]

display.vvv("EXEC %s" % (local_cmd,), host=self.jail)
display.vvv(f"EXEC {local_cmd}", host=self.jail)
local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Expand Down Expand Up @@ -153,7 +153,7 @@ def _prefix_login_path(remote_path):
def put_file(self, in_path, out_path):
""" transfer a file from local to jail """
super(Connection, self).put_file(in_path, out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail)
display.vvv(f"PUT {in_path} TO {out_path}", host=self.jail)

out_path = shlex_quote(self._prefix_login_path(out_path))
try:
Expand All @@ -163,27 +163,27 @@ def put_file(self, in_path, out_path):
else:
count = ''
try:
p = self._buffered_exec_command('dd of=%s bs=%s%s' % (out_path, BUFSIZE, count), stdin=in_file)
p = self._buffered_exec_command(f'dd of={out_path} bs={BUFSIZE}{count}', stdin=in_file)
except OSError:
raise AnsibleError("jail connection requires dd command in the jail")
try:
stdout, stderr = p.communicate()
except Exception:
traceback.print_exc()
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}")
if p.returncode != 0:
raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, to_native(stdout), to_native(stderr)))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{to_native(stdout)}\n{to_native(stderr)}")
except IOError:
raise AnsibleError("file or module does not exist at: %s" % in_path)
raise AnsibleError(f"file or module does not exist at: {in_path}")

def fetch_file(self, in_path, out_path):
""" fetch a file from jail to local """
super(Connection, self).fetch_file(in_path, out_path)
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail)
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.jail)

in_path = shlex_quote(self._prefix_login_path(in_path))
try:
p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE))
p = self._buffered_exec_command(f'dd if={in_path} bs={BUFSIZE}')
except OSError:
raise AnsibleError("jail connection requires dd command in the jail")

Expand All @@ -195,10 +195,10 @@ def fetch_file(self, in_path, out_path):
chunk = p.stdout.read(BUFSIZE)
except Exception:
traceback.print_exc()
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}")
stdout, stderr = p.communicate()
if p.returncode != 0:
raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, to_native(stdout), to_native(stderr)))
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{to_native(stdout)}\n{to_native(stderr)}")

def close(self):
""" terminate the connection; nothing to do here """
Expand Down
Loading

0 comments on commit 6277b0b

Please sign in to comment.