Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lookup plugins: use f-strings #9324

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions changelogs/fragments/9324-fstr-lookup-plugins.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
minor_changes:
- bitwarden lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- chef_databag lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- collection_version lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- consul_kv lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- credstash lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- cyberarkpassword lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- dependent lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- dig lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- dnstxt lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- dsv lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- etcd lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- etcd3 lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- filetree lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- github_app_access_token lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- hiera lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- keyring lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- lastpass lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- lmdb_kv lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- manifold lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- merge_variables lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- onepassword lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- onepassword_doc lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- passwordstore lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- random_pet lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- redis lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- revbitspss lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- shelvefile lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
- tss lookup plugin - use f-strings instead of interpolations or ``format`` (https://github.com/ansible-collections/community.general/pull/9324).
2 changes: 1 addition & 1 deletion plugins/lookup/bitwarden.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def get_field(self, field, search_value, search_field="name", collection_id=None
continue

if matches and not field_matches:
raise AnsibleError("field {field} does not exist in {search_value}".format(field=field, search_value=search_value))
raise AnsibleError(f"field {field} does not exist in {search_value}")

return field_matches

Expand Down
4 changes: 2 additions & 2 deletions plugins/lookup/chef_databag.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ def parse_kv_args(self, args):
setattr(self, arg, parsed)
except ValueError:
raise AnsibleError(
"can't parse arg {0}={1} as string".format(arg, arg_raw)
f"can't parse arg {arg}={arg_raw} as string"
)
if args:
raise AnsibleError(
"unrecognized arguments to with_sequence: %r" % list(args.keys())
f"unrecognized arguments to with_sequence: {list(args.keys())!r}"
)

def run(self, terms, variables=None, **kwargs):
Expand Down
6 changes: 3 additions & 3 deletions plugins/lookup/collection_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,10 @@ def run(self, terms, variables=None, **kwargs):

for term in terms:
if not FQCN_RE.match(term):
raise AnsibleLookupError('"{term}" is not a FQCN'.format(term=term))
raise AnsibleLookupError(f'"{term}" is not a FQCN')

try:
collection_pkg = import_module('ansible_collections.{fqcn}'.format(fqcn=term))
collection_pkg = import_module(f'ansible_collections.{term}')
except ImportError:
# Collection not found
result.append(not_found)
Expand All @@ -127,7 +127,7 @@ def run(self, terms, variables=None, **kwargs):
try:
data = load_collection_meta(collection_pkg, no_version=no_version)
except Exception as exc:
raise AnsibleLookupError('Error while loading metadata for {fqcn}: {error}'.format(fqcn=term, error=exc))
raise AnsibleLookupError(f'Error while loading metadata for {term}: {exc}')

result.append(data.get('version', no_version))

Expand Down
4 changes: 2 additions & 2 deletions plugins/lookup/consul_kv.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def run(self, terms, variables=None, **kwargs):
values.append(to_text(results[1]['Value']))
except Exception as e:
raise AnsibleError(
"Error locating '%s' in kv store. Error was %s" % (term, e))
f"Error locating '{term}' in kv store. Error was {e}")

return values

Expand All @@ -192,7 +192,7 @@ def parse_params(self, term):
if param and len(param) > 0:
name, value = param.split('=')
if name not in paramvals:
raise AnsibleAssertionError("%s not a valid consul lookup parameter" % name)
raise AnsibleAssertionError(f"{name} not a valid consul lookup parameter")
paramvals[name] = value
except (ValueError, AssertionError) as e:
raise AnsibleError(e)
Expand Down
4 changes: 2 additions & 2 deletions plugins/lookup/credstash.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ def run(self, terms, variables=None, **kwargs):
try:
ret.append(credstash.getSecret(term, version, region, table, context=context, **kwargs_pass))
except credstash.ItemNotFound:
raise AnsibleError('Key {0} not found'.format(term))
raise AnsibleError(f'Key {term} not found')
except Exception as e:
raise AnsibleError('Encountered exception while fetching {0}: {1}'.format(term, e))
raise AnsibleError(f'Encountered exception while fetching {term}: {e}')

return ret
14 changes: 7 additions & 7 deletions plugins/lookup/cyberarkpassword.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def __init__(self, appid=None, query=None, output=None, **kwargs):
self.extra_parms = []
for key, value in kwargs.items():
self.extra_parms.append('-p')
self.extra_parms.append("%s=%s" % (key, value))
self.extra_parms.append(f"{key}={value}")

if self.appid is None:
raise AnsibleError("CyberArk Error: No Application ID specified")
Expand All @@ -130,8 +130,8 @@ def get(self):
all_parms = [
CLIPASSWORDSDK_CMD,
'GetPassword',
'-p', 'AppDescs.AppID=%s' % self.appid,
'-p', 'Query=%s' % self.query,
'-p', f'AppDescs.AppID={self.appid}',
'-p', f'Query={self.query}',
'-o', self.output,
'-d', self.b_delimiter]
all_parms.extend(self.extra_parms)
Expand All @@ -144,7 +144,7 @@ def get(self):
b_credential = to_bytes(tmp_output)

if tmp_error:
raise AnsibleError("ERROR => %s " % (tmp_error))
raise AnsibleError(f"ERROR => {tmp_error} ")

if b_credential and b_credential.endswith(b'\n'):
b_credential = b_credential[:-1]
Expand All @@ -164,7 +164,7 @@ def get(self):
except subprocess.CalledProcessError as e:
raise AnsibleError(e.output)
except OSError as e:
raise AnsibleError("ERROR - AIM not installed or clipasswordsdk not in standard location. ERROR=(%s) => %s " % (to_text(e.errno), e.strerror))
raise AnsibleError(f"ERROR - AIM not installed or clipasswordsdk not in standard location. ERROR=({to_text(e.errno)}) => {e.strerror} ")

return [result_dict]

Expand All @@ -177,11 +177,11 @@ class LookupModule(LookupBase):
"""

def run(self, terms, variables=None, **kwargs):
display.vvvv("%s" % terms)
display.vvvv(f"{terms}")
if isinstance(terms, list):
return_values = []
for term in terms:
display.vvvv("Term: %s" % term)
display.vvvv(f"Term: {term}")
cyberark_conn = CyberarkPassword(**term)
return_values.append(cyberark_conn.get())
return return_values
Expand Down
19 changes: 7 additions & 12 deletions plugins/lookup/dependent.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def __evaluate(self, expression, templar, variables):
``variables`` are the variables to use.
"""
templar.available_variables = variables or {}
expression = "{0}{1}{2}".format("{{", expression, "}}")
expression = f"{{{{{expression}}}}}"
russoz marked this conversation as resolved.
Show resolved Hide resolved
if _TEMPLAR_HAS_TEMPLATE_CACHE:
return templar.template(expression, cache=False)
return templar.template(expression)
Expand Down Expand Up @@ -173,8 +173,7 @@ def __process(self, result, terms, index, current, templar, variables):
values = self.__evaluate(expression, templar, variables=vars)
except Exception as e:
raise AnsibleLookupError(
'Caught "{error}" while evaluating {key!r} with item == {item!r}'.format(
error=e, key=key, item=current))
f'Caught "{e}" while evaluating {key!r} with item == {current!r}')

if isinstance(values, Mapping):
for idx, val in sorted(values.items()):
Expand All @@ -186,8 +185,7 @@ def __process(self, result, terms, index, current, templar, variables):
self.__process(result, terms, index + 1, current, templar, variables)
else:
raise AnsibleLookupError(
'Did not obtain dictionary or list while evaluating {key!r} with item == {item!r}, but {type}'.format(
key=key, item=current, type=type(values)))
f'Did not obtain dictionary or list while evaluating {key!r} with item == {current!r}, but {type(values)}')

def run(self, terms, variables=None, **kwargs):
"""Generate list."""
Expand All @@ -201,24 +199,21 @@ def run(self, terms, variables=None, **kwargs):
for index, term in enumerate(terms):
if not isinstance(term, Mapping):
raise AnsibleLookupError(
'Parameter {index} must be a dictionary, got {type}'.format(
index=index, type=type(term)))
f'Parameter {index} must be a dictionary, got {type(term)}')
if len(term) != 1:
raise AnsibleLookupError(
'Parameter {index} must be a one-element dictionary, got {count} elements'.format(
index=index, count=len(term)))
f'Parameter {index} must be a one-element dictionary, got {len(term)} elements')
k, v = list(term.items())[0]
if k in vars_so_far:
raise AnsibleLookupError(
'The variable {key!r} appears more than once'.format(key=k))
f'The variable {k!r} appears more than once')
vars_so_far.add(k)
if isinstance(v, string_types):
data.append((k, v, None))
elif isinstance(v, (Sequence, Mapping)):
data.append((k, None, v))
else:
raise AnsibleLookupError(
'Parameter {key!r} (index {index}) must have a value of type string, dictionary or list, got type {type}'.format(
index=index, key=k, type=type(v)))
f'Parameter {k!r} (index {index}) must have a value of type string, dictionary or list, got type {type(v)}')
self.__process(result, data, 0, {}, templar, variables)
return result
20 changes: 10 additions & 10 deletions plugins/lookup/dig.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ def run(self, terms, variables=None, **kwargs):
try:
rdclass = dns.rdataclass.from_text(self.get_option('class'))
except Exception as e:
raise AnsibleError("dns lookup illegal CLASS: %s" % to_native(e))
raise AnsibleError(f"dns lookup illegal CLASS: {to_native(e)}")
myres.retry_servfail = self.get_option('retry_servfail')

for t in terms:
Expand All @@ -363,7 +363,7 @@ def run(self, terms, variables=None, **kwargs):
nsaddr = dns.resolver.query(ns)[0].address
nameservers.append(nsaddr)
except Exception as e:
raise AnsibleError("dns lookup NS: %s" % to_native(e))
raise AnsibleError(f"dns lookup NS: {to_native(e)}")
continue
if '=' in t:
try:
Expand All @@ -379,7 +379,7 @@ def run(self, terms, variables=None, **kwargs):
try:
rdclass = dns.rdataclass.from_text(arg)
except Exception as e:
raise AnsibleError("dns lookup illegal CLASS: %s" % to_native(e))
raise AnsibleError(f"dns lookup illegal CLASS: {to_native(e)}")
elif opt == 'retry_servfail':
myres.retry_servfail = boolean(arg)
elif opt == 'fail_on_error':
Expand All @@ -400,7 +400,7 @@ def run(self, terms, variables=None, **kwargs):
else:
domains.append(t)

# print "--- domain = {0} qtype={1} rdclass={2}".format(domain, qtype, rdclass)
# print "--- domain = {domain} qtype={qtype} rdclass={rdclass}"

if port:
myres.port = port
Expand All @@ -416,7 +416,7 @@ def run(self, terms, variables=None, **kwargs):
except dns.exception.SyntaxError:
pass
except Exception as e:
raise AnsibleError("dns.reversename unhandled exception %s" % to_native(e))
raise AnsibleError(f"dns.reversename unhandled exception {to_native(e)}")
domains = reversed_domains

if len(domains) > 1:
Expand Down Expand Up @@ -445,25 +445,25 @@ def run(self, terms, variables=None, **kwargs):
ret.append(rd)
except Exception as err:
if fail_on_error:
raise AnsibleError("Lookup failed: %s" % str(err))
raise AnsibleError(f"Lookup failed: {str(err)}")
ret.append(str(err))

except dns.resolver.NXDOMAIN as err:
if fail_on_error:
raise AnsibleError("Lookup failed: %s" % str(err))
raise AnsibleError(f"Lookup failed: {str(err)}")
if not real_empty:
ret.append('NXDOMAIN')
except dns.resolver.NoAnswer as err:
if fail_on_error:
raise AnsibleError("Lookup failed: %s" % str(err))
raise AnsibleError(f"Lookup failed: {str(err)}")
if not real_empty:
ret.append("")
except dns.resolver.Timeout as err:
if fail_on_error:
raise AnsibleError("Lookup failed: %s" % str(err))
raise AnsibleError(f"Lookup failed: {str(err)}")
if not real_empty:
ret.append("")
except dns.exception.DNSException as err:
raise AnsibleError("dns.resolver unhandled exception %s" % to_native(err))
raise AnsibleError(f"dns.resolver unhandled exception {to_native(err)}")

return ret
2 changes: 1 addition & 1 deletion plugins/lookup/dnstxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def run(self, terms, variables=None, **kwargs):
continue
string = ''
except DNSException as e:
raise AnsibleError("dns.resolver unhandled exception %s" % to_native(e))
raise AnsibleError(f"dns.resolver unhandled exception {to_native(e)}")

ret.append(''.join(string))

Expand Down
8 changes: 4 additions & 4 deletions plugins/lookup/dsv.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,17 +135,17 @@ def run(self, terms, variables, **kwargs):
result = []

for term in terms:
display.debug("dsv_lookup term: %s" % term)
display.debug(f"dsv_lookup term: {term}")
try:
path = term.lstrip("[/:]")

if path == "":
raise AnsibleOptionsError("Invalid secret path: %s" % term)
raise AnsibleOptionsError(f"Invalid secret path: {term}")

display.vvv(u"DevOps Secrets Vault GET /secrets/%s" % path)
display.vvv(f"DevOps Secrets Vault GET /secrets/{path}")
result.append(vault.get_secret_json(path))
except SecretsVaultError as error:
raise AnsibleError(
"DevOps Secrets Vault lookup failure: %s" % error.message
f"DevOps Secrets Vault lookup failure: {error.message}"
)
return result
4 changes: 2 additions & 2 deletions plugins/lookup/etcd.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ class Etcd:
def __init__(self, url, version, validate_certs):
self.url = url
self.version = version
self.baseurl = '%s/%s/keys' % (self.url, self.version)
self.baseurl = f'{self.url}/{self.version}/keys'
self.validate_certs = validate_certs

def _parse_node(self, node):
Expand All @@ -125,7 +125,7 @@ def _parse_node(self, node):
return path

def get(self, key):
url = "%s/%s?recursive=true" % (self.baseurl, key)
url = f"{self.baseurl}/{key}?recursive=true"
data = None
value = {}
try:
Expand Down
Loading
Loading