Update pre-commit hook versions

This commit is contained in:
Pedro Algarvio 2024-02-27 10:24:22 +00:00
parent c920ba443d
commit f4549113b1
No known key found for this signature in database
GPG key ID: BB36BF6584A298FF
1867 changed files with 10506 additions and 11419 deletions

View file

@ -6,7 +6,7 @@ exclude: ^(doc/_static/.*|doc/_themes/.*)$
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0 rev: v4.5.0
hooks: hooks:
- id: check-merge-conflict # Check for files that contain merge conflict strings. - id: check-merge-conflict # Check for files that contain merge conflict strings.
- id: trailing-whitespace # Trims trailing whitespace. - id: trailing-whitespace # Trims trailing whitespace.
@ -1397,7 +1397,7 @@ repos:
# ----- Code Formatting -------------------------------------------------------------------------------------------> # ----- Code Formatting ------------------------------------------------------------------------------------------->
- repo: https://github.com/asottile/pyupgrade - repo: https://github.com/asottile/pyupgrade
rev: v2.37.2 rev: v3.15.1
hooks: hooks:
- id: pyupgrade - id: pyupgrade
name: Upgrade code for Py3.8+ name: Upgrade code for Py3.8+
@ -1437,7 +1437,7 @@ repos:
args: [--silent, -E, fix_asserts, -E, fix_docstrings, -E, fix_tornado_imports] args: [--silent, -E, fix_asserts, -E, fix_docstrings, -E, fix_tornado_imports]
- repo: https://github.com/timothycrosley/isort - repo: https://github.com/timothycrosley/isort
rev: 5.12.0 rev: 5.13.2
hooks: hooks:
- id: isort - id: isort
additional_dependencies: ['toml'] additional_dependencies: ['toml']
@ -1450,31 +1450,32 @@ repos:
)$ )$
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 22.6.0 rev: 24.2.0
hooks: hooks:
- id: black - id: black
# This tells pre-commit not to pass files to black. # This tells pre-commit not to pass files to black.
# This should be kept in sync with pyproject.toml # This should be kept in sync with pyproject.toml
exclude: > exclude: >
(?x)^( (?x)^(
salt/client/ssh/ssh_py_shim\.py|
templates/.*| templates/.*|
salt/ext/.*| salt/ext/.*|
)$ )$
- repo: https://github.com/asottile/blacken-docs - repo: https://github.com/asottile/blacken-docs
rev: v1.12.1 rev: 1.16.0
hooks: hooks:
- id: blacken-docs - id: blacken-docs
args: [--skip-errors] args: [--skip-errors]
files: ^doc/.*\.rst files: ^doc/.*\.rst
additional_dependencies: additional_dependencies:
- black==22.6.0 - black==24.2.0
# <---- Code Formatting -------------------------------------------------------------------------------------------- # <---- Code Formatting --------------------------------------------------------------------------------------------
# ----- Security --------------------------------------------------------------------------------------------------> # ----- Security -------------------------------------------------------------------------------------------------->
- repo: https://github.com/PyCQA/bandit - repo: https://github.com/PyCQA/bandit
rev: "1.7.4" rev: "1.7.7"
hooks: hooks:
- id: bandit - id: bandit
alias: bandit-salt alias: bandit-salt
@ -1488,7 +1489,7 @@ repos:
)$ )$
additional_dependencies: ['importlib_metadata<5'] additional_dependencies: ['importlib_metadata<5']
- repo: https://github.com/PyCQA/bandit - repo: https://github.com/PyCQA/bandit
rev: "1.7.4" rev: "1.7.7"
hooks: hooks:
- id: bandit - id: bandit
alias: bandit-tests alias: bandit-tests
@ -1501,7 +1502,7 @@ repos:
# ----- Pre-Commit ------------------------------------------------------------------------------------------------> # ----- Pre-Commit ------------------------------------------------------------------------------------------------>
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.3.0 rev: v1.8.0
hooks: hooks:
- id: mypy - id: mypy
alias: mypy-tools alias: mypy-tools
@ -1518,15 +1519,15 @@ repos:
- types-attrs - types-attrs
- types-pyyaml - types-pyyaml
- types-requests - types-requests
- python-tools-scripts>=0.18.6 - python-tools-scripts==0.18.6
- repo: https://github.com/saltstack/mirrors-nox - repo: https://github.com/saltstack/mirrors-nox
rev: v2021.6.12 rev: v2022.11.21
hooks: hooks:
- id: nox - id: nox
alias: lint-salt alias: lint-salt
name: Lint Salt name: Lint Salt
files: ^((setup|noxfile)|(salt|tasks|tools)/.*)\.py$ files: ^((setup|noxfile)|(salt|tools)/.*)\.py$
exclude: > exclude: >
(?x)^( (?x)^(
templates/.*| templates/.*|
@ -1541,7 +1542,7 @@ repos:
- pip>=20.2.4,<21.2 - pip>=20.2.4,<21.2
- repo: https://github.com/saltstack/mirrors-nox - repo: https://github.com/saltstack/mirrors-nox
rev: v2021.6.12 rev: v2022.11.21
hooks: hooks:
- id: nox - id: nox
alias: lint-tests alias: lint-tests

View file

@ -53,7 +53,7 @@ class LiterateCoding(Directive):
comment; False designates code. comment; False designates code.
""" """
comment_char = "#" # TODO: move this into a directive option comment_char = "#" # TODO: move this into a directive option
comment = re.compile(r"^\s*{}[ \n]".format(comment_char)) comment = re.compile(rf"^\s*{comment_char}[ \n]")
section_test = lambda val: bool(comment.match(val)) section_test = lambda val: bool(comment.match(val))
sections = [] sections = []
@ -136,7 +136,7 @@ class LiterateFormula(LiterateCoding):
formulas_dirs = config.formulas_dirs formulas_dirs = config.formulas_dirs
fpath = sls_path.replace(".", "/") fpath = sls_path.replace(".", "/")
name_options = ("{}.sls".format(fpath), os.path.join(fpath, "init.sls")) name_options = (f"{fpath}.sls", os.path.join(fpath, "init.sls"))
paths = [ paths = [
os.path.join(fdir, fname) os.path.join(fdir, fname)
@ -151,7 +151,7 @@ class LiterateFormula(LiterateCoding):
except OSError: except OSError:
pass pass
raise OSError("Could not find sls file '{}'".format(sls_path)) raise OSError(f"Could not find sls file '{sls_path}'")
class CurrentFormula(Directive): class CurrentFormula(Directive):
@ -196,7 +196,7 @@ class Formula(Directive):
targetnode = nodes.target("", "", ids=["module-" + formname], ismod=True) targetnode = nodes.target("", "", ids=["module-" + formname], ismod=True)
self.state.document.note_explicit_target(targetnode) self.state.document.note_explicit_target(targetnode)
indextext = "{}-formula)".format(formname) indextext = f"{formname}-formula)"
inode = addnodes.index( inode = addnodes.index(
entries=[("single", indextext, "module-" + formname, "")] entries=[("single", indextext, "module-" + formname, "")]
) )
@ -221,9 +221,9 @@ class State(Directive):
formula = env.temp_data.get("salt:formula") formula = env.temp_data.get("salt:formula")
indextext = "{1} ({0}-formula)".format(formula, statename) indextext = f"{statename} ({formula}-formula)"
inode = addnodes.index( inode = addnodes.index(
entries=[("single", indextext, "module-{}".format(statename), "")] entries=[("single", indextext, f"module-{statename}", "")]
) )
return [targetnode, inode] return [targetnode, inode]

View file

@ -59,8 +59,7 @@ the ``execute`` function with the following signature:
.. code-block:: python .. code-block:: python
def execute(opts, data, func, args, kwargs): def execute(opts, data, func, args, kwargs): ...
...
Where the args are: Where the args are:

View file

@ -329,6 +329,7 @@ the case when the dependency is unavailable.
""" """
Cheese execution (or returner/beacon/etc.) module Cheese execution (or returner/beacon/etc.) module
""" """
try: try:
import enzymes import enzymes

View file

@ -364,8 +364,7 @@ the actual testing, such as functions containing assertions, must start with
.. code-block:: python .. code-block:: python
def test_user_present(self): def test_user_present(self): ...
...
When functions in test files are not prepended with ``test_``, the function When functions in test files are not prepended with ``test_``, the function
acts as a normal, helper function and is not run as a test by the test suite. acts as a normal, helper function and is not run as a test by the test suite.

View file

@ -581,7 +581,6 @@ and status; "package" installation, and a ping.
def uptodate(name): def uptodate(name):
""" """
Call the REST endpoint to see if the packages on the "server" are up to date. Call the REST endpoint to see if the packages on the "server" are up to date.
""" """
@ -592,7 +591,6 @@ and status; "package" installation, and a ping.
def package_remove(name): def package_remove(name):
""" """
Remove a "package" on the REST server Remove a "package" on the REST server
""" """

View file

@ -551,15 +551,13 @@ General Deprecations
.. code-block:: python .. code-block:: python
def fcn(msg="", env="base", refresh=True, saltenv="base", **kwargs): def fcn(msg="", env="base", refresh=True, saltenv="base", **kwargs): ...
...
has been changed to has been changed to
.. code-block:: python .. code-block:: python
def fcn(msg="", refresh=True, saltenv="base", **kwargs): def fcn(msg="", refresh=True, saltenv="base", **kwargs): ...
...
- If ``env`` (or ``__env__``) is supplied as a keyword argument to a function - If ``env`` (or ``__env__``) is supplied as a keyword argument to a function
that also accepts arbitrary keyword arguments, then a new warning informs the that also accepts arbitrary keyword arguments, then a new warning informs the
@ -568,8 +566,7 @@ General Deprecations
.. code-block:: python .. code-block:: python
def fcn(msg="", refresh=True, saltenv="base", **kwargs): def fcn(msg="", refresh=True, saltenv="base", **kwargs): ...
...
.. code-block:: python .. code-block:: python
@ -582,8 +579,7 @@ General Deprecations
.. code-block:: python .. code-block:: python
def fcn(msg="", refresh=True, saltenv="base"): def fcn(msg="", refresh=True, saltenv="base"): ...
...
.. code-block:: python .. code-block:: python
@ -597,8 +593,7 @@ General Deprecations
.. code-block:: python .. code-block:: python
def fcn(msg="", refresh=True, saltenv="base"): def fcn(msg="", refresh=True, saltenv="base"): ...
...
.. code-block:: python .. code-block:: python

View file

@ -4,6 +4,7 @@ noxfile
Nox configuration script Nox configuration script
""" """
# pylint: disable=resource-leakage,3rd-party-module-not-gated # pylint: disable=resource-leakage,3rd-party-module-not-gated
import contextlib import contextlib
@ -1787,7 +1788,7 @@ class Recompress:
d_targz = tempd.joinpath(targz.name) d_targz = tempd.joinpath(targz.name)
with tarfile.open(d_tar, "w|") as wfile: with tarfile.open(d_tar, "w|") as wfile:
with tarfile.open(targz, "r:gz") as rfile: with tarfile.open(targz, "r:gz") as rfile:
rfile.extractall(d_src) rfile.extractall(d_src) # nosec
extracted_dir = next(pathlib.Path(d_src).iterdir()) extracted_dir = next(pathlib.Path(d_src).iterdir())
for name in sorted(extracted_dir.rglob("*")): for name in sorted(extracted_dir.rglob("*")):
wfile.add( wfile.add(

View file

@ -12,12 +12,6 @@ import warnings
if sys.platform.startswith("win"): if sys.platform.startswith("win"):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
if sys.version_info < (3,): # pragma: no cover
sys.stderr.write(
"\n\nAfter the Sodium release, 3001, Salt no longer supports Python 2. Exiting.\n\n"
)
sys.stderr.flush()
class NaclImporter: class NaclImporter:
""" """

View file

@ -1,6 +1,7 @@
""" """
Salt compatibility code Salt compatibility code
""" """
# pylint: disable=unused-import # pylint: disable=unused-import
import sys import sys

View file

@ -9,6 +9,7 @@
The ``salt._logging`` package should be imported as soon as possible since salt tweaks The ``salt._logging`` package should be imported as soon as possible since salt tweaks
the python's logging system. the python's logging system.
""" """
from salt._logging.impl import ( from salt._logging.impl import (
DFLT_LOG_DATEFMT, DFLT_LOG_DATEFMT,
DFLT_LOG_DATEFMT_LOGFILE, DFLT_LOG_DATEFMT_LOGFILE,

View file

@ -46,7 +46,6 @@ indicated above, though the model DOES NOT have to be named
'SaltExternalAuthModel'. 'SaltExternalAuthModel'.
""" """
import logging import logging
import os import os
import sys import sys
@ -112,7 +111,7 @@ def __django_auth_setup():
django_module_name, globals(), locals(), "SaltExternalAuthModel" django_module_name, globals(), locals(), "SaltExternalAuthModel"
) )
# pylint: enable=possibly-unused-variable # pylint: enable=possibly-unused-variable
DJANGO_AUTH_CLASS_str = "django_auth_module.{}".format(django_model_name) DJANGO_AUTH_CLASS_str = f"django_auth_module.{django_model_name}"
DJANGO_AUTH_CLASS = eval(DJANGO_AUTH_CLASS_str) # pylint: disable=W0123 DJANGO_AUTH_CLASS = eval(DJANGO_AUTH_CLASS_str) # pylint: disable=W0123

View file

@ -94,7 +94,6 @@ When using ``htdigest`` the ``^realm`` must be set:
""" """
import logging import logging
import os import os

View file

@ -4,7 +4,6 @@ Provide authentication using OpenStack Keystone
:depends: - keystoneclient Python module :depends: - keystoneclient Python module
""" """
try: try:
from keystoneclient.exceptions import AuthorizationFailure, Unauthorized from keystoneclient.exceptions import AuthorizationFailure, Unauthorized
from keystoneclient.v2_0 import client from keystoneclient.v2_0 import client

View file

@ -3,6 +3,7 @@ Provide authentication using simple LDAP binds
:depends: - ldap Python module :depends: - ldap Python module
""" """
import itertools import itertools
import logging import logging
@ -53,15 +54,15 @@ def _config(key, mandatory=True, opts=None):
""" """
try: try:
if opts: if opts:
value = opts["auth.ldap.{}".format(key)] value = opts[f"auth.ldap.{key}"]
else: else:
value = __opts__["auth.ldap.{}".format(key)] value = __opts__[f"auth.ldap.{key}"]
except KeyError: except KeyError:
try: try:
value = __defopts__["auth.ldap.{}".format(key)] value = __defopts__[f"auth.ldap.{key}"]
except KeyError: except KeyError:
if mandatory: if mandatory:
msg = "missing auth.ldap.{} in master config".format(key) msg = f"missing auth.ldap.{key} in master config"
raise SaltInvocationError(msg) raise SaltInvocationError(msg)
return False return False
return value return value
@ -119,13 +120,13 @@ class _LDAPConnection:
schema = "ldaps" if tls else "ldap" schema = "ldaps" if tls else "ldap"
if self.uri == "": if self.uri == "":
self.uri = "{}://{}:{}".format(schema, self.server, self.port) self.uri = f"{schema}://{self.server}:{self.port}"
try: try:
if no_verify: if no_verify:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
self.ldap = ldap.initialize("{}".format(self.uri)) self.ldap = ldap.initialize(f"{self.uri}")
self.ldap.protocol_version = 3 # ldap.VERSION3 self.ldap.protocol_version = 3 # ldap.VERSION3
self.ldap.set_option(ldap.OPT_REFERRALS, 0) # Needed for AD self.ldap.set_option(ldap.OPT_REFERRALS, 0) # Needed for AD

View file

@ -47,7 +47,6 @@ Enable MySQL authentication.
:depends: - MySQL-python Python module :depends: - MySQL-python Python module
""" """
import logging import logging
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View file

@ -22,7 +22,6 @@ structure of a user as above.
""" """
import logging import logging
import salt.utils.http import salt.utils.http

View file

@ -36,7 +36,6 @@ the API key will be updated on all the YubiCloud servers.
""" """
import logging import logging
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View file

@ -3,6 +3,7 @@ Beacon to emit adb device state changes for Android devices
.. versionadded:: 2016.3.0 .. versionadded:: 2016.3.0
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -5,6 +5,7 @@ Beacon to fire event when we notice a AIX user is locked due to many failed logi
:depends: none :depends: none
""" """
import logging import logging
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View file

@ -1,6 +1,7 @@
""" """
Beacon to announce via Bonjour (zeroconf) Beacon to announce via Bonjour (zeroconf)
""" """
import atexit import atexit
import logging import logging
import select import select

View file

@ -130,7 +130,7 @@ except ImportError:
def __virtual__(): def __virtual__():
if os.path.isfile(BTMP): if os.path.isfile(BTMP):
return __virtualname__ return __virtualname__
err_msg = "{} does not exist.".format(BTMP) err_msg = f"{BTMP} does not exist."
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg) log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg return False, err_msg

View file

@ -7,6 +7,7 @@ Beacon to monitor certificate expiration dates from files on the filesystem.
:maturity: new :maturity: new
:depends: OpenSSL :depends: OpenSSL
""" """
import logging import logging
from datetime import datetime from datetime import datetime

View file

@ -5,6 +5,7 @@ Beacon to monitor disk usage.
:depends: python-psutil :depends: python-psutil
""" """
import logging import logging
import re import re
@ -94,7 +95,7 @@ def beacon(config):
# if our mount doesn't end with a $, insert one. # if our mount doesn't end with a $, insert one.
mount_re = mount mount_re = mount
if not mount.endswith("$"): if not mount.endswith("$"):
mount_re = "{}$".format(mount) mount_re = f"{mount}$"
if salt.utils.platform.is_windows(): if salt.utils.platform.is_windows():
# mount_re comes in formatted with a $ at the end # mount_re comes in formatted with a $ at the end

View file

@ -3,6 +3,7 @@ Beacon to emit when a display is available to a linux machine
.. versionadded:: 2016.3.0 .. versionadded:: 2016.3.0
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -4,6 +4,7 @@ Fire an event when over a specified threshold.
.. versionadded:: 2016.11.0 .. versionadded:: 2016.11.0
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -68,7 +68,7 @@ def _get_notifier(config):
Check the context for the notifier and construct it if not present Check the context for the notifier and construct it if not present
""" """
beacon_name = config.get("_beacon_name", "inotify") beacon_name = config.get("_beacon_name", "inotify")
notifier = "{}.notifier".format(beacon_name) notifier = f"{beacon_name}.notifier"
if notifier not in __context__: if notifier not in __context__:
__context__["inotify.queue"] = collections.deque() __context__["inotify.queue"] = collections.deque()
wm = pyinotify.WatchManager() wm = pyinotify.WatchManager()
@ -353,7 +353,7 @@ def beacon(config):
def close(config): def close(config):
config = salt.utils.beacons.list_to_dict(config) config = salt.utils.beacons.list_to_dict(config)
beacon_name = config.get("_beacon_name", "inotify") beacon_name = config.get("_beacon_name", "inotify")
notifier = "{}.notifier".format(beacon_name) notifier = f"{beacon_name}.notifier"
if notifier in __context__: if notifier in __context__:
__context__[notifier].stop() __context__[notifier].stop()
del __context__[notifier] del __context__[notifier]

View file

@ -1,6 +1,7 @@
""" """
A simple beacon to watch journald for specific entries A simple beacon to watch journald for specific entries
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -1,6 +1,7 @@
""" """
Beacon to emit system load averages Beacon to emit system load averages
""" """
import logging import logging
import os import os

View file

@ -4,6 +4,7 @@ Beacon to fire events at specific log messages.
.. versionadded:: 2017.7.0 .. versionadded:: 2017.7.0
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -5,6 +5,7 @@ Beacon to monitor memory usage.
:depends: python-psutil :depends: python-psutil
""" """
import logging import logging
import re import re

View file

@ -298,7 +298,7 @@ def validate(config):
" dictionary".format(fun), " dictionary".format(fun),
) )
if fun not in __salt__: if fun not in __salt__:
return False, "Execution function {} is not availabe!".format(fun) return False, f"Execution function {fun} is not availabe!"
return True, "Valid configuration for the napal beacon!" return True, "Valid configuration for the napal beacon!"

View file

@ -3,6 +3,7 @@ Beacon to monitor statistics from ethernet adapters
.. versionadded:: 2015.5.0 .. versionadded:: 2015.5.0
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -3,6 +3,7 @@ Watch for pkgs that have upgrades, then fire an event.
.. versionadded:: 2016.3.0 .. versionadded:: 2016.3.0
""" """
import logging import logging
__virtualname__ = "pkg" __virtualname__ = "pkg"

View file

@ -7,6 +7,7 @@ Example beacon to use with salt-proxy
proxy_example: proxy_example:
endpoint: beacon endpoint: beacon
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -1,6 +1,7 @@
""" """
Send events covering process status Send events covering process status
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -24,6 +24,7 @@ See example config below.
- test.ping - test.ping
- interval: 3600 # seconds - interval: 3600 # seconds
""" """
import salt.utils.beacons import salt.utils.beacons
@ -44,7 +45,7 @@ def validate(config):
# a simple str is taking as the single function with no args / kwargs # a simple str is taking as the single function with no args / kwargs
fun = config["salt_fun"] fun = config["salt_fun"]
if fun not in __salt__: if fun not in __salt__:
return False, "{} not in __salt__".format(fun) return False, f"{fun} not in __salt__"
else: else:
for entry in config["salt_fun"]: for entry in config["salt_fun"]:
if isinstance(entry, dict): if isinstance(entry, dict):
@ -55,7 +56,7 @@ def validate(config):
if not isinstance(args_kwargs_dict[key], list): if not isinstance(args_kwargs_dict[key], list):
return ( return (
False, False,
"args key for fun {} must be list".format(fun), f"args key for fun {fun} must be list",
) )
elif key == "kwargs": elif key == "kwargs":
if not isinstance(args_kwargs_dict[key], list): if not isinstance(args_kwargs_dict[key], list):
@ -69,19 +70,19 @@ def validate(config):
if not isinstance(key_value, dict): if not isinstance(key_value, dict):
return ( return (
False, False,
"{} is not a key / value pair".format(key_value), f"{key_value} is not a key / value pair",
) )
else: else:
return ( return (
False, False,
"key {} not allowed under fun {}".format(key, fun), f"key {key} not allowed under fun {fun}",
) )
else: else:
# entry must be function itself # entry must be function itself
fun = entry fun = entry
if fun not in __salt__: if fun not in __salt__:
return False, "{} not in __salt__".format(fun) return False, f"{fun} not in __salt__"
return True, "valid config" return True, "valid config"

View file

@ -4,6 +4,7 @@
.. versionadded:: 2015.8.3 .. versionadded:: 2015.8.3
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons
@ -22,9 +23,9 @@ def _run_proxy_processes(proxies):
result = {} result = {}
if not __salt__["salt_proxy.is_running"](proxy)["result"]: if not __salt__["salt_proxy.is_running"](proxy)["result"]:
__salt__["salt_proxy.configure_proxy"](proxy, start=True) __salt__["salt_proxy.configure_proxy"](proxy, start=True)
result[proxy] = "Proxy {} was started".format(proxy) result[proxy] = f"Proxy {proxy} was started"
else: else:
msg = "Proxy {} is already running".format(proxy) msg = f"Proxy {proxy} is already running"
result[proxy] = msg result[proxy] = msg
log.debug(msg) log.debug(msg)
ret.append(result) ret.append(result)

View file

@ -8,6 +8,7 @@ Monitor temperature, humidity and pressure using the SenseHat of a Raspberry Pi
:maturity: new :maturity: new
:depends: sense_hat Python module :depends: sense_hat Python module
""" """
import logging import logging
import re import re
@ -72,7 +73,7 @@ def beacon(config):
config = salt.utils.beacons.list_to_dict(config) config = salt.utils.beacons.list_to_dict(config)
for sensor in config.get("sensors", {}): for sensor in config.get("sensors", {}):
sensor_function = "sensehat.get_{}".format(sensor) sensor_function = f"sensehat.get_{sensor}"
if sensor_function not in __salt__: if sensor_function not in __salt__:
log.error("No sensor for meassuring %s. Skipping.", sensor) log.error("No sensor for meassuring %s. Skipping.", sensor)
continue continue
@ -94,6 +95,6 @@ def beacon(config):
current_value = __salt__[sensor_function]() current_value = __salt__[sensor_function]()
if not sensor_min <= current_value <= sensor_max: if not sensor_min <= current_value <= sensor_max:
ret.append({"tag": "sensehat/{}".format(sensor), sensor: current_value}) ret.append({"tag": f"sensehat/{sensor}", sensor: current_value})
return ret return ret

View file

@ -1,6 +1,7 @@
""" """
Send events covering service status Send events covering service status
""" """
import logging import logging
import os import os
import time import time

View file

@ -1,6 +1,7 @@
""" """
Watch the shell commands being executed actively. This beacon requires strace. Watch the shell commands being executed actively. This beacon requires strace.
""" """
import logging import logging
import time import time
@ -72,7 +73,7 @@ def beacon(config):
__context__[pkey] = {} __context__[pkey] = {}
for pid in track_pids: for pid in track_pids:
if pid not in __context__[pkey]: if pid not in __context__[pkey]:
cmd = ["strace", "-f", "-e", "execve", "-p", "{}".format(pid)] cmd = ["strace", "-f", "-e", "execve", "-p", f"{pid}"]
__context__[pkey][pid] = {} __context__[pkey][pid] = {}
__context__[pkey][pid]["vt"] = salt.utils.vt.Terminal( __context__[pkey][pid]["vt"] = salt.utils.vt.Terminal(
cmd, cmd,

View file

@ -17,6 +17,7 @@ Beacon that fires events on image import/delete.
- interval: 60 - interval: 60
- startup_import_event: True - startup_import_event: True
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -17,6 +17,7 @@ Beacon that fires events on vm state changes
- interval: 60 - interval: 60
- startup_create_event: True - startup_create_event: True
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -87,6 +87,7 @@ markers for specific list items:
to check the minion log for errors after configuring this beacon. to check the minion log for errors after configuring this beacon.
""" """
import datetime import datetime
import logging import logging
@ -142,7 +143,7 @@ def beacon(config):
for func in entry: for func in entry:
ret[func] = {} ret[func] = {}
try: try:
data = __salt__["status.{}".format(func)]() data = __salt__[f"status.{func}"]()
except salt.exceptions.CommandExecutionError as exc: except salt.exceptions.CommandExecutionError as exc:
log.debug( log.debug(
"Status beacon attempted to process function %s " "Status beacon attempted to process function %s "
@ -165,8 +166,6 @@ def beacon(config):
except TypeError: except TypeError:
ret[func][item] = data[int(item)] ret[func][item] = data[int(item)]
except KeyError as exc: except KeyError as exc:
ret[ ret[func] = f"Status beacon is incorrectly configured: {exc}"
func
] = "Status beacon is incorrectly configured: {}".format(exc)
return [{"tag": ctime, "data": ret}] return [{"tag": ctime, "data": ret}]

View file

@ -5,6 +5,7 @@ Beacon to monitor swap usage.
:depends: python-psutil :depends: python-psutil
""" """
import logging import logging
import re import re

View file

@ -4,6 +4,7 @@ Beacon to emit Telegram messages
Requires the python-telegram-bot library Requires the python-telegram-bot library
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -1,6 +1,7 @@
""" """
Beacon to emit Twilio text messages Beacon to emit Twilio text messages
""" """
import logging import logging
import salt.utils.beacons import salt.utils.beacons

View file

@ -159,7 +159,7 @@ except ImportError:
def __virtual__(): def __virtual__():
if os.path.isfile(WTMP): if os.path.isfile(WTMP):
return __virtualname__ return __virtualname__
err_msg = "{} does not exist.".format(WTMP) err_msg = f"{WTMP} does not exist."
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg) log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg return False, err_msg

View file

@ -4,7 +4,6 @@ Loader mechanism for caching data, with data expiration, etc.
.. versionadded:: 2016.11.0 .. versionadded:: 2016.11.0
""" """
import logging import logging
import time import time
@ -70,7 +69,7 @@ class Cache:
def __lazy_init(self): def __lazy_init(self):
self._modules = salt.loader.cache(self.opts) self._modules = salt.loader.cache(self.opts)
fun = "{}.init_kwargs".format(self.driver) fun = f"{self.driver}.init_kwargs"
if fun in self.modules: if fun in self.modules:
self._kwargs = self.modules[fun](self._kwargs) self._kwargs = self.modules[fun](self._kwargs)
else: else:
@ -141,7 +140,7 @@ class Cache:
Raises an exception if cache driver detected an error accessing data Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). in the cache backend (auth, permissions, etc).
""" """
fun = "{}.store".format(self.driver) fun = f"{self.driver}.store"
return self.modules[fun](bank, key, data, **self._kwargs) return self.modules[fun](bank, key, data, **self._kwargs)
def fetch(self, bank, key): def fetch(self, bank, key):
@ -165,7 +164,7 @@ class Cache:
Raises an exception if cache driver detected an error accessing data Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). in the cache backend (auth, permissions, etc).
""" """
fun = "{}.fetch".format(self.driver) fun = f"{self.driver}.fetch"
return self.modules[fun](bank, key, **self._kwargs) return self.modules[fun](bank, key, **self._kwargs)
def updated(self, bank, key): def updated(self, bank, key):
@ -189,7 +188,7 @@ class Cache:
Raises an exception if cache driver detected an error accessing data Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). in the cache backend (auth, permissions, etc).
""" """
fun = "{}.updated".format(self.driver) fun = f"{self.driver}.updated"
return self.modules[fun](bank, key, **self._kwargs) return self.modules[fun](bank, key, **self._kwargs)
def flush(self, bank, key=None): def flush(self, bank, key=None):
@ -210,7 +209,7 @@ class Cache:
Raises an exception if cache driver detected an error accessing data Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). in the cache backend (auth, permissions, etc).
""" """
fun = "{}.flush".format(self.driver) fun = f"{self.driver}.flush"
return self.modules[fun](bank, key=key, **self._kwargs) return self.modules[fun](bank, key=key, **self._kwargs)
def list(self, bank): def list(self, bank):
@ -229,7 +228,7 @@ class Cache:
Raises an exception if cache driver detected an error accessing data Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). in the cache backend (auth, permissions, etc).
""" """
fun = "{}.list".format(self.driver) fun = f"{self.driver}.list"
return self.modules[fun](bank, **self._kwargs) return self.modules[fun](bank, **self._kwargs)
def contains(self, bank, key=None): def contains(self, bank, key=None):
@ -254,7 +253,7 @@ class Cache:
Raises an exception if cache driver detected an error accessing data Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). in the cache backend (auth, permissions, etc).
""" """
fun = "{}.contains".format(self.driver) fun = f"{self.driver}.contains"
return self.modules[fun](bank, key, **self._kwargs) return self.modules[fun](bank, key, **self._kwargs)
@ -289,7 +288,7 @@ class MemCache(Cache):
break break
def _get_storage_id(self): def _get_storage_id(self):
fun = "{}.storage_id".format(self.driver) fun = f"{self.driver}.storage_id"
if fun in self.modules: if fun in self.modules:
return self.modules[fun](self.kwargs) return self.modules[fun](self.kwargs)
else: else:

View file

@ -141,16 +141,14 @@ def store(bank, key, data):
Store a key value. Store a key value.
""" """
_init_client() _init_client()
etcd_key = "{}/{}/{}".format(path_prefix, bank, key) etcd_key = f"{path_prefix}/{bank}/{key}"
etcd_tstamp_key = "{}/{}/{}".format(path_prefix, bank, key + _tstamp_suffix) etcd_tstamp_key = f"{path_prefix}/{bank}/{key + _tstamp_suffix}"
try: try:
value = salt.payload.dumps(data) value = salt.payload.dumps(data)
client.write(etcd_key, base64.b64encode(value)) client.write(etcd_key, base64.b64encode(value))
client.write(etcd_tstamp_key, int(time.time())) client.write(etcd_tstamp_key, int(time.time()))
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
raise SaltCacheError( raise SaltCacheError(f"There was an error writing the key, {etcd_key}: {exc}")
"There was an error writing the key, {}: {}".format(etcd_key, exc)
)
def fetch(bank, key): def fetch(bank, key):
@ -158,16 +156,14 @@ def fetch(bank, key):
Fetch a key value. Fetch a key value.
""" """
_init_client() _init_client()
etcd_key = "{}/{}/{}".format(path_prefix, bank, key) etcd_key = f"{path_prefix}/{bank}/{key}"
try: try:
value = client.read(etcd_key).value value = client.read(etcd_key).value
return salt.payload.loads(base64.b64decode(value)) return salt.payload.loads(base64.b64decode(value))
except etcd.EtcdKeyNotFound: except etcd.EtcdKeyNotFound:
return {} return {}
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
raise SaltCacheError( raise SaltCacheError(f"There was an error reading the key, {etcd_key}: {exc}")
"There was an error reading the key, {}: {}".format(etcd_key, exc)
)
def flush(bank, key=None): def flush(bank, key=None):
@ -176,11 +172,11 @@ def flush(bank, key=None):
""" """
_init_client() _init_client()
if key is None: if key is None:
etcd_key = "{}/{}".format(path_prefix, bank) etcd_key = f"{path_prefix}/{bank}"
tstamp_key = None tstamp_key = None
else: else:
etcd_key = "{}/{}/{}".format(path_prefix, bank, key) etcd_key = f"{path_prefix}/{bank}/{key}"
tstamp_key = "{}/{}/{}".format(path_prefix, bank, key + _tstamp_suffix) tstamp_key = f"{path_prefix}/{bank}/{key + _tstamp_suffix}"
try: try:
client.read(etcd_key) client.read(etcd_key)
except etcd.EtcdKeyNotFound: except etcd.EtcdKeyNotFound:
@ -190,9 +186,7 @@ def flush(bank, key=None):
client.delete(tstamp_key) client.delete(tstamp_key)
client.delete(etcd_key, recursive=True) client.delete(etcd_key, recursive=True)
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
raise SaltCacheError( raise SaltCacheError(f"There was an error removing the key, {etcd_key}: {exc}")
"There was an error removing the key, {}: {}".format(etcd_key, exc)
)
def _walk(r): def _walk(r):
@ -218,14 +212,14 @@ def ls(bank):
bank. bank.
""" """
_init_client() _init_client()
path = "{}/{}".format(path_prefix, bank) path = f"{path_prefix}/{bank}"
try: try:
return _walk(client.read(path)) return _walk(client.read(path))
except etcd.EtcdKeyNotFound: except etcd.EtcdKeyNotFound:
return [] return []
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
raise SaltCacheError( raise SaltCacheError(
'There was an error getting the key "{}": {}'.format(bank, exc) f'There was an error getting the key "{bank}": {exc}'
) from exc ) from exc
@ -242,9 +236,7 @@ def contains(bank, key):
except etcd.EtcdKeyNotFound: except etcd.EtcdKeyNotFound:
return False return False
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
raise SaltCacheError( raise SaltCacheError(f"There was an error getting the key, {etcd_key}: {exc}")
"There was an error getting the key, {}: {}".format(etcd_key, exc)
)
def updated(bank, key): def updated(bank, key):
@ -252,13 +244,11 @@ def updated(bank, key):
Return Unix Epoch based timestamp of when the bank/key was updated. Return Unix Epoch based timestamp of when the bank/key was updated.
""" """
_init_client() _init_client()
tstamp_key = "{}/{}/{}".format(path_prefix, bank, key + _tstamp_suffix) tstamp_key = f"{path_prefix}/{bank}/{key + _tstamp_suffix}"
try: try:
value = client.read(tstamp_key).value value = client.read(tstamp_key).value
return int(value) return int(value)
except etcd.EtcdKeyNotFound: except etcd.EtcdKeyNotFound:
return None return None
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
raise SaltCacheError( raise SaltCacheError(f"There was an error reading the key, {tstamp_key}: {exc}")
"There was an error reading the key, {}: {}".format(tstamp_key, exc)
)

24
salt/cache/localfs.py vendored
View file

@ -51,10 +51,10 @@ def store(bank, key, data, cachedir):
except OSError as exc: except OSError as exc:
if exc.errno != errno.EEXIST: if exc.errno != errno.EEXIST:
raise SaltCacheError( raise SaltCacheError(
"The cache directory, {}, could not be created: {}".format(base, exc) f"The cache directory, {base}, could not be created: {exc}"
) )
outfile = os.path.join(base, "{}.p".format(key)) outfile = os.path.join(base, f"{key}.p")
tmpfh, tmpfname = tempfile.mkstemp(dir=base) tmpfh, tmpfname = tempfile.mkstemp(dir=base)
os.close(tmpfh) os.close(tmpfh)
try: try:
@ -64,7 +64,7 @@ def store(bank, key, data, cachedir):
salt.utils.atomicfile.atomic_rename(tmpfname, outfile) salt.utils.atomicfile.atomic_rename(tmpfname, outfile)
except OSError as exc: except OSError as exc:
raise SaltCacheError( raise SaltCacheError(
"There was an error writing the cache file, {}: {}".format(base, exc) f"There was an error writing the cache file, {base}: {exc}"
) )
@ -73,7 +73,7 @@ def fetch(bank, key, cachedir):
Fetch information from a file. Fetch information from a file.
""" """
inkey = False inkey = False
key_file = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) key_file = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p")
if not os.path.isfile(key_file): if not os.path.isfile(key_file):
# The bank includes the full filename, and the key is inside the file # The bank includes the full filename, and the key is inside the file
key_file = os.path.join(cachedir, os.path.normpath(bank) + ".p") key_file = os.path.join(cachedir, os.path.normpath(bank) + ".p")
@ -90,7 +90,7 @@ def fetch(bank, key, cachedir):
return salt.payload.load(fh_) return salt.payload.load(fh_)
except OSError as exc: except OSError as exc:
raise SaltCacheError( raise SaltCacheError(
'There was an error reading the cache file "{}": {}'.format(key_file, exc) f'There was an error reading the cache file "{key_file}": {exc}'
) )
@ -98,7 +98,7 @@ def updated(bank, key, cachedir):
""" """
Return the epoch of the mtime for this cache file Return the epoch of the mtime for this cache file
""" """
key_file = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) key_file = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p")
if not os.path.isfile(key_file): if not os.path.isfile(key_file):
log.warning('Cache file "%s" does not exist', key_file) log.warning('Cache file "%s" does not exist', key_file)
return None return None
@ -106,7 +106,7 @@ def updated(bank, key, cachedir):
return int(os.path.getmtime(key_file)) return int(os.path.getmtime(key_file))
except OSError as exc: except OSError as exc:
raise SaltCacheError( raise SaltCacheError(
'There was an error reading the mtime for "{}": {}'.format(key_file, exc) f'There was an error reading the mtime for "{key_file}": {exc}'
) )
@ -124,12 +124,12 @@ def flush(bank, key=None, cachedir=None):
return False return False
shutil.rmtree(target) shutil.rmtree(target)
else: else:
target = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) target = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p")
if not os.path.isfile(target): if not os.path.isfile(target):
return False return False
os.remove(target) os.remove(target)
except OSError as exc: except OSError as exc:
raise SaltCacheError('There was an error removing "{}": {}'.format(target, exc)) raise SaltCacheError(f'There was an error removing "{target}": {exc}')
return True return True
@ -143,9 +143,7 @@ def list_(bank, cachedir):
try: try:
items = os.listdir(base) items = os.listdir(base)
except OSError as exc: except OSError as exc:
raise SaltCacheError( raise SaltCacheError(f'There was an error accessing directory "{base}": {exc}')
'There was an error accessing directory "{}": {}'.format(base, exc)
)
ret = [] ret = []
for item in items: for item in items:
if item.endswith(".p"): if item.endswith(".p"):
@ -163,5 +161,5 @@ def contains(bank, key, cachedir):
base = os.path.join(cachedir, os.path.normpath(bank)) base = os.path.join(cachedir, os.path.normpath(bank))
return os.path.isdir(base) return os.path.isdir(base)
else: else:
keyfile = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) keyfile = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p")
return os.path.isfile(keyfile) return os.path.isfile(keyfile)

View file

@ -151,7 +151,6 @@ Cluster Configuration Example:
cache.redis.separator: '@' cache.redis.separator: '@'
""" """
import itertools import itertools
import logging import logging
import time import time
@ -352,7 +351,7 @@ def _get_banks_to_remove(redis_server, bank, path=""):
A simple tree traversal algorithm that builds the list of banks to remove, A simple tree traversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree. starting from an arbitrary node in the tree.
""" """
current_path = bank if not path else "{path}/{bank}".format(path=path, bank=bank) current_path = bank if not path else f"{path}/{bank}"
bank_paths_to_remove = [current_path] bank_paths_to_remove = [current_path]
# as you got here, you'll be removed # as you got here, you'll be removed

View file

@ -3,6 +3,7 @@ Encapsulate the different transports available to Salt.
This includes client side transport, for the ReqServer and the Publisher This includes client side transport, for the ReqServer and the Publisher
""" """
import logging import logging
import os import os
import time import time

View file

@ -6,7 +6,6 @@
""" """
import logging import logging
import salt.client.netapi import salt.client.netapi

View file

@ -188,7 +188,7 @@ class Batch:
if next_: if next_:
if not self.quiet: if not self.quiet:
salt.utils.stringutils.print_cli( salt.utils.stringutils.print_cli(
"\nExecuting run on {}\n".format(sorted(next_)) f"\nExecuting run on {sorted(next_)}\n"
) )
# create a new iterator for this batch of minions # create a new iterator for this batch of minions
return_value = self.opts.get("return", self.opts.get("ret", "")) return_value = self.opts.get("return", self.opts.get("ret", ""))

View file

@ -75,7 +75,7 @@ class BaseCaller:
docs[name] = func.__doc__ docs[name] = func.__doc__
for name in sorted(docs): for name in sorted(docs):
if name.startswith(self.opts.get("fun", "")): if name.startswith(self.opts.get("fun", "")):
salt.utils.stringutils.print_cli("{}:\n{}\n".format(name, docs[name])) salt.utils.stringutils.print_cli(f"{name}:\n{docs[name]}\n")
def print_grains(self): def print_grains(self):
""" """
@ -130,7 +130,7 @@ class BaseCaller:
salt.minion.get_proc_dir(self.opts["cachedir"]), ret["jid"] salt.minion.get_proc_dir(self.opts["cachedir"]), ret["jid"]
) )
if fun not in self.minion.functions: if fun not in self.minion.functions:
docs = self.minion.functions["sys.doc"]("{}*".format(fun)) docs = self.minion.functions["sys.doc"](f"{fun}*")
if docs: if docs:
docs[fun] = self.minion.functions.missing_fun_string(fun) docs[fun] = self.minion.functions.missing_fun_string(fun)
ret["out"] = "nested" ret["out"] = "nested"
@ -194,20 +194,16 @@ class BaseCaller:
executors = [executors] executors = [executors]
try: try:
for name in executors: for name in executors:
fname = "{}.execute".format(name) fname = f"{name}.execute"
if fname not in self.minion.executors: if fname not in self.minion.executors:
raise SaltInvocationError( raise SaltInvocationError(f"Executor '{name}' is not available")
"Executor '{}' is not available".format(name)
)
ret["return"] = self.minion.executors[fname]( ret["return"] = self.minion.executors[fname](
self.opts, data, func, args, kwargs self.opts, data, func, args, kwargs
) )
if ret["return"] is not None: if ret["return"] is not None:
break break
except TypeError as exc: except TypeError as exc:
sys.stderr.write( sys.stderr.write(f"\nPassed invalid arguments: {exc}.\n\nUsage:\n")
"\nPassed invalid arguments: {}.\n\nUsage:\n".format(exc)
)
salt.utils.stringutils.print_cli(func.__doc__) salt.utils.stringutils.print_cli(func.__doc__)
active_level = LOG_LEVELS.get( active_level = LOG_LEVELS.get(
self.opts["log_level"].lower(), logging.ERROR self.opts["log_level"].lower(), logging.ERROR
@ -235,7 +231,7 @@ class BaseCaller:
retcode = salt.defaults.exitcodes.EX_GENERIC retcode = salt.defaults.exitcodes.EX_GENERIC
ret["retcode"] = retcode ret["retcode"] = retcode
except (CommandExecutionError) as exc: except CommandExecutionError as exc:
msg = "Error running '{0}': {1}\n" msg = "Error running '{0}': {1}\n"
active_level = LOG_LEVELS.get(self.opts["log_level"].lower(), logging.ERROR) active_level = LOG_LEVELS.get(self.opts["log_level"].lower(), logging.ERROR)
if active_level <= logging.DEBUG: if active_level <= logging.DEBUG:
@ -272,7 +268,7 @@ class BaseCaller:
continue continue
try: try:
ret["success"] = True ret["success"] = True
self.minion.returners["{}.returner".format(returner)](ret) self.minion.returners[f"{returner}.returner"](ret)
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
pass pass

View file

@ -68,7 +68,7 @@ class SaltCP:
except OSError as exc: except OSError as exc:
if exc.errno == errno.ENOENT: if exc.errno == errno.ENOENT:
# Path does not exist # Path does not exist
sys.stderr.write("{} does not exist\n".format(path)) sys.stderr.write(f"{path} does not exist\n")
sys.exit(42) sys.exit(42)
elif exc.errno in (errno.EINVAL, errno.ENOTDIR): elif exc.errno in (errno.EINVAL, errno.ENOTDIR):
# Path is a file (EINVAL on Windows, ENOTDIR otherwise) # Path is a file (EINVAL on Windows, ENOTDIR otherwise)
@ -97,7 +97,7 @@ class SaltCP:
Take a path and return the contents of the file as a string Take a path and return the contents of the file as a string
""" """
if not os.path.isfile(fn_): if not os.path.isfile(fn_):
err = "The referenced file, {} is not available.".format(fn_) err = f"The referenced file, {fn_} is not available."
sys.stderr.write(err + "\n") sys.stderr.write(err + "\n")
sys.exit(42) sys.exit(42)
with salt.utils.files.fopen(fn_, "r") as fp_: with salt.utils.files.fopen(fn_, "r") as fp_:
@ -211,12 +211,10 @@ class SaltCP:
log.debug( log.debug(
"Copying %s to %starget '%s' as %s%s", "Copying %s to %starget '%s' as %s%s",
fn_, fn_,
"{} ".format(selected_target_option) f"{selected_target_option} " if selected_target_option else "",
if selected_target_option
else "",
tgt, tgt,
remote_path, remote_path,
" (chunk #{})".format(index) if append else "", f" (chunk #{index})" if append else "",
) )
args = [ args = [
tgt, tgt,
@ -261,11 +259,13 @@ class SaltCP:
log.debug( log.debug(
"Creating empty dir %s on %starget '%s'", "Creating empty dir %s on %starget '%s'",
dirname, dirname,
"{} ".format( (
selected_target_option "{} ".format(
) # pylint: disable=str-format-in-logging selected_target_option
if selected_target_option ) # pylint: disable=str-format-in-logging
else "", if selected_target_option
else ""
),
tgt, tgt,
) )
args = [tgt, "cp.recv_chunked", [remote_path, None], timeout] args = [tgt, "cp.recv_chunked", [remote_path, None], timeout]

View file

@ -2,7 +2,6 @@
Make me some salt! Make me some salt!
""" """
import logging import logging
import os import os
import warnings import warnings

View file

@ -7,7 +7,6 @@
.. versionadded:: 2015.8.0 .. versionadded:: 2015.8.0
""" """
import salt.spm import salt.spm
import salt.utils.parsers as parsers import salt.utils.parsers as parsers
from salt.utils.verify import verify_env from salt.utils.verify import verify_env

View file

@ -8,7 +8,6 @@ The data structure needs to be:
'key': '<read in the key file>'} 'key': '<read in the key file>'}
""" """
import logging import logging
# The components here are simple, and they need to be and stay simple, we # The components here are simple, and they need to be and stay simple, we

View file

@ -382,10 +382,10 @@ class SyncClientMixin(ClientStateMixin):
try: try:
data["return"] = func(*args, **kwargs) data["return"] = func(*args, **kwargs)
except TypeError as exc: except TypeError as exc:
data[ data["return"] = (
"return" "\nPassed invalid arguments: {}\n\nUsage:\n{}".format(
] = "\nPassed invalid arguments: {}\n\nUsage:\n{}".format( exc, func.__doc__
exc, func.__doc__ )
) )
try: try:
data["success"] = self.context.get("retcode", 0) == 0 data["success"] = self.context.get("retcode", 0) == 0

View file

@ -48,7 +48,7 @@ class NetapiClient:
for fun in self.netapi: for fun in self.netapi:
if fun.endswith(".start"): if fun.endswith(".start"):
name = "RunNetapi({})".format(self.netapi[fun].__module__) name = f"RunNetapi({self.netapi[fun].__module__})"
log.info("Starting %s", name) log.info("Starting %s", name)
self.process_manager.add_process( self.process_manager.add_process(
RunNetapi, args=(self.opts, fun), name=name RunNetapi, args=(self.opts, fun), name=name

View file

@ -783,9 +783,9 @@ class SSH(MultiprocessingStateMixin):
data["return"] = data.get("stdout") data["return"] = data.get("stdout")
else: else:
data["return"] = data.get("stderr", data.get("stdout")) data["return"] = data.get("stderr", data.get("stdout"))
data[ data["jid"] = (
"jid" jid # make the jid in the payload the same as the jid in the tag
] = jid # make the jid in the payload the same as the jid in the tag )
self.event.fire_event( self.event.fire_event(
data, salt.utils.event.tagify([jid, "ret", host], "job") data, salt.utils.event.tagify([jid, "ret", host], "job")
) )
@ -923,9 +923,9 @@ class SSH(MultiprocessingStateMixin):
data["return"] = data.get("stdout") data["return"] = data.get("stdout")
else: else:
data["return"] = data.get("stderr", data.get("stdout")) data["return"] = data.get("stderr", data.get("stdout"))
data[ data["jid"] = (
"jid" jid # make the jid in the payload the same as the jid in the tag
] = jid # make the jid in the payload the same as the jid in the tag )
self.event.fire_event( self.event.fire_event(
data, salt.utils.event.tagify([jid, "ret", host], "job") data, salt.utils.event.tagify([jid, "ret", host], "job")
) )

View file

@ -170,7 +170,7 @@ def unpack_thin(thin_path):
""" """
tfile = tarfile.TarFile.gzopen(thin_path) tfile = tarfile.TarFile.gzopen(thin_path)
old_umask = os.umask(0o077) # pylint: disable=blacklisted-function old_umask = os.umask(0o077) # pylint: disable=blacklisted-function
tfile.extractall(path=OPTIONS.saltdir) tfile.extractall(path=OPTIONS.saltdir) # nosec
tfile.close() tfile.close()
os.umask(old_umask) # pylint: disable=blacklisted-function os.umask(old_umask) # pylint: disable=blacklisted-function
try: try:
@ -197,7 +197,7 @@ def unpack_ext(ext_path):
) )
tfile = tarfile.TarFile.gzopen(ext_path) tfile = tarfile.TarFile.gzopen(ext_path)
old_umask = os.umask(0o077) # pylint: disable=blacklisted-function old_umask = os.umask(0o077) # pylint: disable=blacklisted-function
tfile.extractall(path=modcache) tfile.extractall(path=modcache) # nosec
tfile.close() tfile.close()
os.umask(old_umask) # pylint: disable=blacklisted-function os.umask(old_umask) # pylint: disable=blacklisted-function
os.unlink(ext_path) os.unlink(ext_path)

View file

@ -5,7 +5,6 @@ to be easily rewritten to execute in a way that makes them do the same tasks
as ZeroMQ salt, but via ssh. as ZeroMQ salt, but via ssh.
""" """
import copy import copy
import logging import logging

View file

@ -8,6 +8,7 @@ SSH wrapper module for the ``cmdmod`` execution module.
value of the minion setting. value of the minion setting.
This is the same for the ``state`` and `cp`` wrappers. This is the same for the ``state`` and `cp`` wrappers.
""" """
import logging import logging
import os.path import os.path
import shlex import shlex

View file

@ -2,7 +2,6 @@
Return/control aspects of the grains data Return/control aspects of the grains data
""" """
import math import math
import salt.utils.data import salt.utils.data

View file

@ -8,7 +8,6 @@ Wrapper function for mine operations for salt-ssh
accessing the regular mine as well. accessing the regular mine as well.
""" """
import copy import copy
import logging import logging

View file

@ -2,6 +2,7 @@
The top level interface used to translate configuration data back to the The top level interface used to translate configuration data back to the
correct cloud modules correct cloud modules
""" """
import copy import copy
import glob import glob
import logging import logging

View file

@ -1,6 +1,7 @@
""" """
Primary interfaces for the salt-cloud system Primary interfaces for the salt-cloud system
""" """
# Need to get data from 4 sources! # Need to get data from 4 sources!
# CLI options # CLI options
# salt cloud config - CONFIG_DIR + '/cloud' # salt cloud config - CONFIG_DIR + '/cloud'
@ -174,11 +175,11 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser):
msg = "The following virtual machines are set to be destroyed:\n" msg = "The following virtual machines are set to be destroyed:\n"
names = set() names = set()
for alias, drivers in matching.items(): for alias, drivers in matching.items():
msg += " {}:\n".format(alias) msg += f" {alias}:\n"
for driver, vms in drivers.items(): for driver, vms in drivers.items():
msg += " {}:\n".format(driver) msg += f" {driver}:\n"
for name in vms: for name in vms:
msg += " {}\n".format(name) msg += f" {name}\n"
names.add(name) names.add(name)
try: try:
if self.print_confirm(msg): if self.print_confirm(msg):
@ -212,7 +213,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser):
key, value = name.split("=", 1) key, value = name.split("=", 1)
kwargs[key] = value kwargs[key] = value
else: else:
msg += " {}\n".format(name) msg += f" {name}\n"
machines.append(name) machines.append(name)
names = machines names = machines
@ -255,7 +256,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser):
elif self.options.set_password: elif self.options.set_password:
username = self.credential_username username = self.credential_username
provider_name = "salt.cloud.provider.{}".format(self.credential_provider) provider_name = f"salt.cloud.provider.{self.credential_provider}"
# TODO: check if provider is configured # TODO: check if provider is configured
# set the password # set the password
salt.utils.cloud.store_password_in_keyring(provider_name, username) salt.utils.cloud.store_password_in_keyring(provider_name, username)
@ -275,7 +276,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser):
# display profile errors # display profile errors
msg += "Found the following errors:\n" msg += "Found the following errors:\n"
for profile_name, error in dmap["errors"].items(): for profile_name, error in dmap["errors"].items():
msg += " {}: {}\n".format(profile_name, error) msg += f" {profile_name}: {error}\n"
sys.stderr.write(msg) sys.stderr.write(msg)
sys.stderr.flush() sys.stderr.flush()
@ -283,17 +284,17 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser):
if "existing" in dmap: if "existing" in dmap:
msg += "The following virtual machines already exist:\n" msg += "The following virtual machines already exist:\n"
for name in dmap["existing"]: for name in dmap["existing"]:
msg += " {}\n".format(name) msg += f" {name}\n"
if dmap["create"]: if dmap["create"]:
msg += "The following virtual machines are set to be created:\n" msg += "The following virtual machines are set to be created:\n"
for name in dmap["create"]: for name in dmap["create"]:
msg += " {}\n".format(name) msg += f" {name}\n"
if "destroy" in dmap: if "destroy" in dmap:
msg += "The following virtual machines are set to be destroyed:\n" msg += "The following virtual machines are set to be destroyed:\n"
for name in dmap["destroy"]: for name in dmap["destroy"]:
msg += " {}\n".format(name) msg += f" {name}\n"
if not dmap["create"] and not dmap.get("destroy", None): if not dmap["create"] and not dmap.get("destroy", None):
if not dmap.get("existing", None): if not dmap.get("existing", None):
@ -382,7 +383,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser):
# This is a salt cloud system exit # This is a salt cloud system exit
if exc.exit_code > 0: if exc.exit_code > 0:
# the exit code is bigger than 0, it's an error # the exit code is bigger than 0, it's an error
msg = "Error: {}".format(msg) msg = f"Error: {msg}"
self.exit(exc.exit_code, msg.format(exc).rstrip() + "\n") self.exit(exc.exit_code, msg.format(exc).rstrip() + "\n")
# It's not a system exit but it's an error we can # It's not a system exit but it's an error we can
# handle # handle

View file

@ -412,9 +412,7 @@ def get_image(vm_):
if vm_image and str(vm_image) in images: if vm_image and str(vm_image) in images:
return images[vm_image]["ImageId"] return images[vm_image]["ImageId"]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.")
"The specified image, '{}', could not be found.".format(vm_image)
)
def get_securitygroup(vm_): def get_securitygroup(vm_):
@ -432,7 +430,7 @@ def get_securitygroup(vm_):
if securitygroup and str(securitygroup) in sgs: if securitygroup and str(securitygroup) in sgs:
return sgs[securitygroup]["SecurityGroupId"] return sgs[securitygroup]["SecurityGroupId"]
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified security group, '{}', could not be found.".format(securitygroup) f"The specified security group, '{securitygroup}', could not be found."
) )
@ -451,9 +449,7 @@ def get_size(vm_):
if vm_size and str(vm_size) in sizes: if vm_size and str(vm_size) in sizes:
return sizes[vm_size]["InstanceTypeId"] return sizes[vm_size]["InstanceTypeId"]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.")
"The specified size, '{}', could not be found.".format(vm_size)
)
def __get_location(vm_): def __get_location(vm_):
@ -471,7 +467,7 @@ def __get_location(vm_):
if vm_location and str(vm_location) in locations: if vm_location and str(vm_location) in locations:
return locations[vm_location]["RegionId"] return locations[vm_location]["RegionId"]
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified location, '{}', could not be found.".format(vm_location) f"The specified location, '{vm_location}', could not be found."
) )
@ -575,7 +571,7 @@ def create_node(kwargs):
"HostName", "HostName",
"Password", "Password",
"SystemDisk.Category", "SystemDisk.Category",
"VSwitchId" "VSwitchId",
# 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId' # 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId'
] ]
@ -920,7 +916,7 @@ def _get_node(name):
) )
# Just a little delay between attempts... # Just a little delay between attempts...
time.sleep(0.5) time.sleep(0.5)
raise SaltCloudNotFound("The specified instance {} not found".format(name)) raise SaltCloudNotFound(f"The specified instance {name} not found")
def show_image(kwargs, call=None): def show_image(kwargs, call=None):
@ -982,7 +978,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -1001,7 +997,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -20,6 +20,7 @@ Use of this module requires the ``apikey``, ``secretkey``, ``host`` and
driver: cloudstack driver: cloudstack
""" """
# pylint: disable=function-redefined # pylint: disable=function-redefined
import logging import logging
@ -473,7 +474,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
args={"name": name}, args={"name": name},
) )
@ -498,7 +499,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"detaching volume", "detaching volume",
"salt/cloud/{}/detaching".format(volume.name), f"salt/cloud/{volume.name}/detaching",
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
args={"name": volume.name}, args={"name": volume.name},
) )
@ -509,7 +510,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"detached volume", "detached volume",
"salt/cloud/{}/detached".format(volume.name), f"salt/cloud/{volume.name}/detached",
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
args={"name": volume.name}, args={"name": volume.name},
) )
@ -518,7 +519,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying volume", "destroying volume",
"salt/cloud/{}/destroying".format(volume.name), f"salt/cloud/{volume.name}/destroying",
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
args={"name": volume.name}, args={"name": volume.name},
) )
@ -529,7 +530,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed volume", "destroyed volume",
"salt/cloud/{}/destroyed".format(volume.name), f"salt/cloud/{volume.name}/destroyed",
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
args={"name": volume.name}, args={"name": volume.name},
) )
@ -544,7 +545,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
args={"name": name}, args={"name": name},
) )

View file

@ -296,11 +296,9 @@ def query(
location = get_location() location = get_location()
if not requesturl: if not requesturl:
endpoint = provider.get( endpoint = provider.get("endpoint", f"ec2.{location}.{service_url}")
"endpoint", "ec2.{}.{}".format(location, service_url)
)
requesturl = "https://{}/".format(endpoint) requesturl = f"https://{endpoint}/"
endpoint = urllib.parse.urlparse(requesturl).netloc endpoint = urllib.parse.urlparse(requesturl).netloc
endpoint_path = urllib.parse.urlparse(requesturl).path endpoint_path = urllib.parse.urlparse(requesturl).path
else: else:
@ -1479,7 +1477,7 @@ def _create_eni_if_necessary(interface, vm_):
eni_desc = result[1] eni_desc = result[1]
if not eni_desc or not eni_desc.get("networkInterfaceId"): if not eni_desc or not eni_desc.get("networkInterfaceId"):
raise SaltCloudException("Failed to create interface: {}".format(result)) raise SaltCloudException(f"Failed to create interface: {result}")
eni_id = eni_desc.get("networkInterfaceId") eni_id = eni_desc.get("networkInterfaceId")
log.debug("Created network interface %s inst %s", eni_id, interface["DeviceIndex"]) log.debug("Created network interface %s inst %s", eni_id, interface["DeviceIndex"])
@ -1750,11 +1748,11 @@ def _param_from_config(key, data):
if isinstance(data, dict): if isinstance(data, dict):
for k, v in data.items(): for k, v in data.items():
param.update(_param_from_config("{}.{}".format(key, k), v)) param.update(_param_from_config(f"{key}.{k}", v))
elif isinstance(data, list) or isinstance(data, tuple): elif isinstance(data, list) or isinstance(data, tuple):
for idx, conf_item in enumerate(data): for idx, conf_item in enumerate(data):
prefix = "{}.{}".format(key, idx) prefix = f"{key}.{idx}"
param.update(_param_from_config(prefix, conf_item)) param.update(_param_from_config(prefix, conf_item))
else: else:
@ -1869,7 +1867,7 @@ def request_instance(vm_=None, call=None):
params[spot_prefix + "SecurityGroup.1"] = ex_securitygroup params[spot_prefix + "SecurityGroup.1"] = ex_securitygroup
else: else:
for counter, sg_ in enumerate(ex_securitygroup): for counter, sg_ in enumerate(ex_securitygroup):
params[spot_prefix + "SecurityGroup.{}".format(counter)] = sg_ params[spot_prefix + f"SecurityGroup.{counter}"] = sg_
ex_iam_profile = iam_profile(vm_) ex_iam_profile = iam_profile(vm_)
if ex_iam_profile: if ex_iam_profile:
@ -1904,7 +1902,7 @@ def request_instance(vm_=None, call=None):
params[spot_prefix + "SecurityGroupId.1"] = ex_securitygroupid params[spot_prefix + "SecurityGroupId.1"] = ex_securitygroupid
else: else:
for counter, sg_ in enumerate(ex_securitygroupid): for counter, sg_ in enumerate(ex_securitygroupid):
params[spot_prefix + "SecurityGroupId.{}".format(counter)] = sg_ params[spot_prefix + f"SecurityGroupId.{counter}"] = sg_
placementgroup_ = get_placementgroup(vm_) placementgroup_ = get_placementgroup(vm_)
if placementgroup_ is not None: if placementgroup_ is not None:
@ -2043,9 +2041,9 @@ def request_instance(vm_=None, call=None):
else: else:
dev_index = len(dev_list) dev_index = len(dev_list)
# Add the device name in since it wasn't already there # Add the device name in since it wasn't already there
params[ params[f"{spot_prefix}BlockDeviceMapping.{dev_index}.DeviceName"] = (
"{}BlockDeviceMapping.{}.DeviceName".format(spot_prefix, dev_index) rd_name
] = rd_name )
# Set the termination value # Set the termination value
termination_key = "{}BlockDeviceMapping.{}.Ebs.DeleteOnTermination".format( termination_key = "{}BlockDeviceMapping.{}.Ebs.DeleteOnTermination".format(
@ -2508,7 +2506,7 @@ def wait_for_instance(
for line in comps[0].splitlines(): for line in comps[0].splitlines():
if not line: if not line:
continue continue
keys += "\n{} {}".format(ip_address, line) keys += f"\n{ip_address} {line}"
with salt.utils.files.fopen(known_hosts_file, "a") as fp_: with salt.utils.files.fopen(known_hosts_file, "a") as fp_:
fp_.write(salt.utils.stringutils.to_str(keys)) fp_.write(salt.utils.stringutils.to_str(keys))
@ -2562,7 +2560,7 @@ def _validate_key_path_and_mode(key_filename):
if not os.path.exists(key_filename): if not os.path.exists(key_filename):
raise SaltCloudSystemExit( raise SaltCloudSystemExit(
"The EC2 key file '{}' does not exist.\n".format(key_filename) f"The EC2 key file '{key_filename}' does not exist.\n"
) )
key_mode = stat.S_IMODE(os.stat(key_filename).st_mode) key_mode = stat.S_IMODE(os.stat(key_filename).st_mode)
@ -2751,7 +2749,7 @@ def create(vm_=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"setting tags", "setting tags",
"salt/cloud/spot_request_{}/tagging".format(sir_id), f"salt/cloud/spot_request_{sir_id}/tagging",
args={"tags": spot_request_tags}, args={"tags": spot_request_tags},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2923,7 +2921,7 @@ def create(vm_=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"setting tags", "setting tags",
"salt/cloud/block_volume_{}/tagging".format(str(volid)), f"salt/cloud/block_volume_{str(volid)}/tagging",
args={"tags": tags}, args={"tags": tags},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -3053,7 +3051,7 @@ def stop(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"stopping instance", "stopping instance",
"salt/cloud/{}/stopping".format(name), f"salt/cloud/{name}/stopping",
args={"name": name, "instance_id": instance_id}, args={"name": name, "instance_id": instance_id},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -3087,7 +3085,7 @@ def start(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"starting instance", "starting instance",
"salt/cloud/{}/starting".format(name), f"salt/cloud/{name}/starting",
args={"name": name, "instance_id": instance_id}, args={"name": name, "instance_id": instance_id},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -3162,8 +3160,8 @@ def set_tags(
tags = kwargs tags = kwargs
for idx, (tag_k, tag_v) in enumerate(tags.items()): for idx, (tag_k, tag_v) in enumerate(tags.items()):
params["Tag.{}.Key".format(idx)] = tag_k params[f"Tag.{idx}.Key"] = tag_k
params["Tag.{}.Value".format(idx)] = tag_v params[f"Tag.{idx}.Value"] = tag_v
attempts = 0 attempts = 0
while attempts < aws.AWS_MAX_RETRIES: while attempts < aws.AWS_MAX_RETRIES:
@ -3209,7 +3207,7 @@ def set_tags(
return settags return settags
raise SaltCloudSystemExit("Failed to set tags on {}!".format(name)) raise SaltCloudSystemExit(f"Failed to set tags on {name}!")
def get_tags( def get_tags(
@ -3291,7 +3289,7 @@ def del_tags(
params = {"Action": "DeleteTags", "ResourceId.1": instance_id} params = {"Action": "DeleteTags", "ResourceId.1": instance_id}
for idx, tag in enumerate(kwargs["tags"].split(",")): for idx, tag in enumerate(kwargs["tags"].split(",")):
params["Tag.{}.Key".format(idx)] = tag params[f"Tag.{idx}.Key"] = tag
aws.query( aws.query(
params, params,
@ -3355,7 +3353,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name, "instance_id": instance_id}, args={"name": name, "instance_id": instance_id},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -3376,7 +3374,7 @@ def destroy(name, call=None):
"rename_on_destroy", get_configured_provider(), __opts__, search_global=False "rename_on_destroy", get_configured_provider(), __opts__, search_global=False
) )
if rename_on_destroy is not False: if rename_on_destroy is not False:
newname = "{}-DEL{}".format(name, uuid.uuid4().hex) newname = f"{name}-DEL{uuid.uuid4().hex}"
rename(name, kwargs={"newname": newname}, call="action") rename(name, kwargs={"newname": newname}, call="action")
log.info( log.info(
"Machine will be identified as %s until it has been cleaned up.", newname "Machine will be identified as %s until it has been cleaned up.", newname
@ -3409,7 +3407,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name, "instance_id": instance_id}, args={"name": name, "instance_id": instance_id},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -4055,8 +4053,8 @@ def _toggle_delvol(
if volume_id is not None and volume_id != item["ebs"]["volumeId"]: if volume_id is not None and volume_id != item["ebs"]["volumeId"]:
continue continue
params["BlockDeviceMapping.{}.DeviceName".format(idx)] = device_name params[f"BlockDeviceMapping.{idx}.DeviceName"] = device_name
params["BlockDeviceMapping.{}.Ebs.DeleteOnTermination".format(idx)] = value params[f"BlockDeviceMapping.{idx}.Ebs.DeleteOnTermination"] = value
aws.query( aws.query(
params, params,
@ -4476,7 +4474,7 @@ def describe_volumes(kwargs=None, call=None):
if "volume_id" in kwargs: if "volume_id" in kwargs:
volume_id = kwargs["volume_id"].split(",") volume_id = kwargs["volume_id"].split(",")
for volume_index, volume_id in enumerate(volume_id): for volume_index, volume_id in enumerate(volume_id):
params["VolumeId.{}".format(volume_index)] = volume_id params[f"VolumeId.{volume_index}"] = volume_id
log.debug(params) log.debug(params)
@ -4795,17 +4793,17 @@ def describe_snapshots(kwargs=None, call=None):
if "snapshot_id" in kwargs: if "snapshot_id" in kwargs:
snapshot_ids = kwargs["snapshot_id"].split(",") snapshot_ids = kwargs["snapshot_id"].split(",")
for snapshot_index, snapshot_id in enumerate(snapshot_ids): for snapshot_index, snapshot_id in enumerate(snapshot_ids):
params["SnapshotId.{}".format(snapshot_index)] = snapshot_id params[f"SnapshotId.{snapshot_index}"] = snapshot_id
if "owner" in kwargs: if "owner" in kwargs:
owners = kwargs["owner"].split(",") owners = kwargs["owner"].split(",")
for owner_index, owner in enumerate(owners): for owner_index, owner in enumerate(owners):
params["Owner.{}".format(owner_index)] = owner params[f"Owner.{owner_index}"] = owner
if "restorable_by" in kwargs: if "restorable_by" in kwargs:
restorable_bys = kwargs["restorable_by"].split(",") restorable_bys = kwargs["restorable_by"].split(",")
for restorable_by_index, restorable_by in enumerate(restorable_bys): for restorable_by_index, restorable_by in enumerate(restorable_bys):
params["RestorableBy.{}".format(restorable_by_index)] = restorable_by params[f"RestorableBy.{restorable_by_index}"] = restorable_by
log.debug(params) log.debug(params)
@ -5012,11 +5010,11 @@ def _parse_pricing(url, name):
"storageGiB", "storageGiB",
"USD", "USD",
): ):
price_js = price_js.replace(keyword, '"{}"'.format(keyword)) price_js = price_js.replace(keyword, f'"{keyword}"')
for keyword in ("region", "price", "size"): for keyword in ("region", "price", "size"):
price_js = price_js.replace(keyword, '"{}"'.format(keyword)) price_js = price_js.replace(keyword, f'"{keyword}"')
price_js = price_js.replace('"{}"s'.format(keyword), '"{}s"'.format(keyword)) price_js = price_js.replace(f'"{keyword}"s', f'"{keyword}s"')
price_js = price_js.replace('""', '"') price_js = price_js.replace('""', '"')
@ -5030,7 +5028,7 @@ def _parse_pricing(url, name):
sizes[size["size"]] = size sizes[size["size"]] = size
regions[region["region"]] = sizes regions[region["region"]] = sizes
outfile = os.path.join(__opts__["cachedir"], "ec2-pricing-{}.p".format(name)) outfile = os.path.join(__opts__["cachedir"], f"ec2-pricing-{name}.p")
with salt.utils.files.fopen(outfile, "w") as fho: with salt.utils.files.fopen(outfile, "w") as fho:
salt.utils.msgpack.dump(regions, fho) salt.utils.msgpack.dump(regions, fho)
@ -5092,7 +5090,7 @@ def show_pricing(kwargs=None, call=None):
else: else:
name = "linux" name = "linux"
pricefile = os.path.join(__opts__["cachedir"], "ec2-pricing-{}.p".format(name)) pricefile = os.path.join(__opts__["cachedir"], f"ec2-pricing-{name}.p")
if not os.path.isfile(pricefile): if not os.path.isfile(pricefile):
update_pricing({"type": name}, "function") update_pricing({"type": name}, "function")

View file

@ -43,6 +43,7 @@ Example Provider Configuration
:maintainer: Russell Tolle <russ.tolle@gmail.com> :maintainer: Russell Tolle <russ.tolle@gmail.com>
:depends: libcloud >= 1.0.0 :depends: libcloud >= 1.0.0
""" """
# pylint: disable=function-redefined # pylint: disable=function-redefined
import logging import logging
@ -185,7 +186,7 @@ def get_conn():
"service_account_private_key", provider, __opts__ "service_account_private_key", provider, __opts__
) )
gce = driver(email, private_key, project=project) gce = driver(email, private_key, project=project)
gce.connection.user_agent_append("{}/{}".format(_UA_PRODUCT, _UA_VERSION)) gce.connection.user_agent_append(f"{_UA_PRODUCT}/{_UA_VERSION}")
return gce return gce
@ -543,7 +544,7 @@ def _parse_allow(allow):
pairs = p.split(":") pairs = p.split(":")
if pairs[0].lower() not in ["tcp", "udp", "icmp"]: if pairs[0].lower() not in ["tcp", "udp", "icmp"]:
raise SaltCloudSystemExit( raise SaltCloudSystemExit(
"Unsupported protocol {}. Must be tcp, udp, or icmp.".format(pairs[0]) f"Unsupported protocol {pairs[0]}. Must be tcp, udp, or icmp."
) )
if len(pairs) == 1 or pairs[0].lower() == "icmp": if len(pairs) == 1 or pairs[0].lower() == "icmp":
seen_protos[pairs[0]] = [] seen_protos[pairs[0]] = []
@ -1698,7 +1699,6 @@ def delete_disk(kwargs=None, call=None):
def create_disk(kwargs=None, call=None): def create_disk(kwargs=None, call=None):
""" """
Create a new persistent disk. Must specify `disk_name` and `location`, Create a new persistent disk. Must specify `disk_name` and `location`,
and optionally can specify 'disk_type' as pd-standard or pd-ssd, which and optionally can specify 'disk_type' as pd-standard or pd-ssd, which
@ -2014,7 +2014,7 @@ def reboot(vm_name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"reboot instance", "reboot instance",
"salt/cloud/{}/rebooting".format(vm_name), f"salt/cloud/{vm_name}/rebooting",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2025,7 +2025,7 @@ def reboot(vm_name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"reboot instance", "reboot instance",
"salt/cloud/{}/rebooted".format(vm_name), f"salt/cloud/{vm_name}/rebooted",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2056,7 +2056,7 @@ def start(vm_name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"start instance", "start instance",
"salt/cloud/{}/starting".format(vm_name), f"salt/cloud/{vm_name}/starting",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2067,7 +2067,7 @@ def start(vm_name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"start instance", "start instance",
"salt/cloud/{}/started".format(vm_name), f"salt/cloud/{vm_name}/started",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2096,7 +2096,7 @@ def stop(vm_name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"stop instance", "stop instance",
"salt/cloud/{}/stopping".format(vm_name), f"salt/cloud/{vm_name}/stopping",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2107,7 +2107,7 @@ def stop(vm_name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"stop instance", "stop instance",
"salt/cloud/{}/stopped".format(vm_name), f"salt/cloud/{vm_name}/stopped",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2145,12 +2145,12 @@ def destroy(vm_name, call=None):
exc, exc,
exc_info_on_loglevel=logging.DEBUG, exc_info_on_loglevel=logging.DEBUG,
) )
raise SaltCloudSystemExit("Could not find instance {}.".format(vm_name)) raise SaltCloudSystemExit(f"Could not find instance {vm_name}.")
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"delete instance", "delete instance",
"salt/cloud/{}/deleting".format(vm_name), f"salt/cloud/{vm_name}/deleting",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2186,11 +2186,11 @@ def destroy(vm_name, call=None):
exc, exc,
exc_info_on_loglevel=logging.DEBUG, exc_info_on_loglevel=logging.DEBUG,
) )
raise SaltCloudSystemExit("Could not destroy instance {}.".format(vm_name)) raise SaltCloudSystemExit(f"Could not destroy instance {vm_name}.")
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"delete instance", "delete instance",
"salt/cloud/{}/deleted".format(vm_name), f"salt/cloud/{vm_name}/deleted",
args={"name": vm_name}, args={"name": vm_name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2279,7 +2279,7 @@ def create_attach_volumes(name, kwargs, call=None):
letter = ord("a") - 1 letter = ord("a") - 1
for idx, volume in enumerate(volumes): for idx, volume in enumerate(volumes):
volume_name = "{}-sd{}".format(name, chr(letter + 2 + idx)) volume_name = f"{name}-sd{chr(letter + 2 + idx)}"
volume_dict = { volume_dict = {
"disk_name": volume_name, "disk_name": volume_name,

View file

@ -417,7 +417,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -428,7 +428,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -536,7 +536,7 @@ def _query(
path += action path += action
if command: if command:
path += "/{}".format(command) path += f"/{command}"
log.debug("GoGrid URL: %s", path) log.debug("GoGrid URL: %s", path)

View file

@ -16,6 +16,7 @@ Use of this module requires the ``key`` parameter to be set.
driver: hetzner driver: hetzner
""" """
# pylint: disable=invalid-name,function-redefined # pylint: disable=invalid-name,function-redefined
@ -469,22 +470,22 @@ def start(name, call=None, wait=True):
client = _connect_client() client = _connect_client()
server = client.servers.get_by_name(name) server = client.servers.get_by_name(name)
if server is None: if server is None:
return "Instance {} doesn't exist.".format(name) return f"Instance {name} doesn't exist."
server.power_on() server.power_on()
if wait and not wait_until(name, "running"): if wait and not wait_until(name, "running"):
return "Instance {} doesn't start.".format(name) return f"Instance {name} doesn't start."
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"started instance", "started instance",
"salt/cloud/{}/started".format(name), f"salt/cloud/{name}/started",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
) )
return {"Started": "{} was started.".format(name)} return {"Started": f"{name} was started."}
def stop(name, call=None, wait=True): def stop(name, call=None, wait=True):
@ -503,22 +504,22 @@ def stop(name, call=None, wait=True):
client = _connect_client() client = _connect_client()
server = client.servers.get_by_name(name) server = client.servers.get_by_name(name)
if server is None: if server is None:
return "Instance {} doesn't exist.".format(name) return f"Instance {name} doesn't exist."
server.power_off() server.power_off()
if wait and not wait_until(name, "off"): if wait and not wait_until(name, "off"):
return "Instance {} doesn't stop.".format(name) return f"Instance {name} doesn't stop."
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"stopped instance", "stopped instance",
"salt/cloud/{}/stopped".format(name), f"salt/cloud/{name}/stopped",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
) )
return {"Stopped": "{} was stopped.".format(name)} return {"Stopped": f"{name} was stopped."}
def reboot(name, call=None, wait=True): def reboot(name, call=None, wait=True):
@ -539,14 +540,14 @@ def reboot(name, call=None, wait=True):
client = _connect_client() client = _connect_client()
server = client.servers.get_by_name(name) server = client.servers.get_by_name(name)
if server is None: if server is None:
return "Instance {} doesn't exist.".format(name) return f"Instance {name} doesn't exist."
server.reboot() server.reboot()
if wait and not wait_until(name, "running"): if wait and not wait_until(name, "running"):
return "Instance {} doesn't start.".format(name) return f"Instance {name} doesn't start."
return {"Rebooted": "{} was rebooted.".format(name)} return {"Rebooted": f"{name} was rebooted."}
def destroy(name, call=None): def destroy(name, call=None):
@ -567,12 +568,12 @@ def destroy(name, call=None):
client = _connect_client() client = _connect_client()
server = client.servers.get_by_name(name) server = client.servers.get_by_name(name)
if server is None: if server is None:
return "Instance {} doesn't exist.".format(name) return f"Instance {name} doesn't exist."
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -582,14 +583,14 @@ def destroy(name, call=None):
if node["state"] == "running": if node["state"] == "running":
stop(name, call="action", wait=False) stop(name, call="action", wait=False)
if not wait_until(name, "off"): if not wait_until(name, "off"):
return {"Error": "Unable to destroy {}, command timed out".format(name)} return {"Error": f"Unable to destroy {name}, command timed out"}
server.delete() server.delete()
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -602,7 +603,7 @@ def destroy(name, call=None):
__opts__, __opts__,
) )
return {"Destroyed": "{} was destroyed.".format(name)} return {"Destroyed": f"{name} was destroyed."}
def resize(name, kwargs, call=None): def resize(name, kwargs, call=None):
@ -623,7 +624,7 @@ def resize(name, kwargs, call=None):
client = _connect_client() client = _connect_client()
server = client.servers.get_by_name(name) server = client.servers.get_by_name(name)
if server is None: if server is None:
return "Instance {} doesn't exist.".format(name) return f"Instance {name} doesn't exist."
# Check the configuration # Check the configuration
size = kwargs.get("size", None) size = kwargs.get("size", None)
@ -637,7 +638,7 @@ def resize(name, kwargs, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"resizing instance", "resizing instance",
"salt/cloud/{}/resizing".format(name), f"salt/cloud/{name}/resizing",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -647,17 +648,17 @@ def resize(name, kwargs, call=None):
if node["state"] == "running": if node["state"] == "running":
stop(name, call="action", wait=False) stop(name, call="action", wait=False)
if not wait_until(name, "off"): if not wait_until(name, "off"):
return {"Error": "Unable to resize {}, command timed out".format(name)} return {"Error": f"Unable to resize {name}, command timed out"}
server.change_type(server_type, kwargs.get("upgrade_disk", False)) server.change_type(server_type, kwargs.get("upgrade_disk", False))
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"resizing instance", "resizing instance",
"salt/cloud/{}/resized".format(name), f"salt/cloud/{name}/resized",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
) )
return {"Resized": "{} was resized.".format(name)} return {"Resized": f"{name} was resized."}

View file

@ -161,9 +161,7 @@ def get_image(vm_):
images[vm_image]["name"] = images[vm_image]["id"] images[vm_image]["name"] = images[vm_image]["id"]
return images[vm_image] return images[vm_image]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.")
"The specified image, '{}', could not be found.".format(vm_image)
)
def get_size(vm_): def get_size(vm_):
@ -178,9 +176,7 @@ def get_size(vm_):
if vm_size and str(vm_size) in sizes: if vm_size and str(vm_size) in sizes:
return sizes[vm_size] return sizes[vm_size]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.")
"The specified size, '{}', could not be found.".format(vm_size)
)
def query_instance(vm_=None, call=None): def query_instance(vm_=None, call=None):
@ -375,11 +371,11 @@ def create_node(**kwargs):
if metadata is not None: if metadata is not None:
for key, value in metadata.items(): for key, value in metadata.items():
create_data["metadata.{}".format(key)] = value create_data[f"metadata.{key}"] = value
if tag is not None: if tag is not None:
for key, value in tag.items(): for key, value in tag.items():
create_data["tag.{}".format(key)] = value create_data[f"tag.{key}"] = value
if firewall_enabled is not None: if firewall_enabled is not None:
create_data["firewall_enabled"] = firewall_enabled create_data["firewall_enabled"] = firewall_enabled
@ -419,7 +415,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -435,7 +431,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -532,7 +528,6 @@ def take_action(
method="GET", method="GET",
location=DEFAULT_LOCATION, location=DEFAULT_LOCATION,
): ):
""" """
take action call used by start,stop, reboot take action call used by start,stop, reboot
:param name: name given to the machine :param name: name given to the machine
@ -921,11 +916,11 @@ def avail_images(call=None):
get_configured_provider(), get_configured_provider(),
__opts__, __opts__,
search_global=False, search_global=False,
default="{}{}/{}/images".format(DEFAULT_LOCATION, JOYENT_API_HOST_SUFFIX, user), default=f"{DEFAULT_LOCATION}{JOYENT_API_HOST_SUFFIX}/{user}/images",
) )
if not img_url.startswith("http://") and not img_url.startswith("https://"): if not img_url.startswith("http://") and not img_url.startswith("https://"):
img_url = "{}://{}".format(_get_proto(), img_url) img_url = f"{_get_proto()}://{img_url}"
rcode, data = query(command="my/images", method="GET") rcode, data = query(command="my/images", method="GET")
log.debug(data) log.debug(data)
@ -1078,7 +1073,7 @@ def get_location_path(
:param location: joyent data center location :param location: joyent data center location
:return: url :return: url
""" """
return "{}://{}{}".format(_get_proto(), location, api_host_suffix) return f"{_get_proto()}://{location}{api_host_suffix}"
def query(action=None, command=None, args=None, method="GET", location=None, data=None): def query(action=None, command=None, args=None, method="GET", location=None, data=None):
@ -1152,7 +1147,7 @@ def query(action=None, command=None, args=None, method="GET", location=None, dat
path += action path += action
if command: if command:
path += "/{}".format(command) path += f"/{command}"
log.debug("User: '%s' on PATH: %s", user, path) log.debug("User: '%s' on PATH: %s", user, path)
@ -1175,9 +1170,9 @@ def query(action=None, command=None, args=None, method="GET", location=None, dat
signed = base64.b64encode(signed) signed = base64.b64encode(signed)
user_arr = user.split("/") user_arr = user.split("/")
if len(user_arr) == 1: if len(user_arr) == 1:
keyid = "/{}/keys/{}".format(user_arr[0], ssh_keyname) keyid = f"/{user_arr[0]}/keys/{ssh_keyname}"
elif len(user_arr) == 2: elif len(user_arr) == 2:
keyid = "/{}/users/{}/keys/{}".format(user_arr[0], user_arr[1], ssh_keyname) keyid = f"/{user_arr[0]}/users/{user_arr[1]}/keys/{ssh_keyname}"
else: else:
log.error("Malformed user string") log.error("Malformed user string")

View file

@ -258,7 +258,7 @@ def get_domain_ips(domain, ip_source):
log.info("Exception polling address %s", error) log.info("Exception polling address %s", error)
return ips return ips
for (name, val) in addresses.items(): for name, val in addresses.items():
if val["addrs"]: if val["addrs"]:
for addr in val["addrs"]: for addr in val["addrs"]:
tp = to_ip_addr_type(addr["type"]) tp = to_ip_addr_type(addr["type"])
@ -332,7 +332,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"starting create", "starting create",
"salt/cloud/{}/creating".format(name), f"salt/cloud/{name}/creating",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"creating", vm_, ["name", "profile", "provider", "driver"] "creating", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -345,7 +345,7 @@ def create(vm_):
) )
if key_filename is not None and not os.path.isfile(key_filename): if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The defined key_filename '{}' does not exist".format(key_filename) f"The defined key_filename '{key_filename}' does not exist"
) )
vm_["key_filename"] = key_filename vm_["key_filename"] = key_filename
# wait_for_instance requires private_key # wait_for_instance requires private_key
@ -374,7 +374,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"requesting instance", "requesting instance",
"salt/cloud/{}/requesting".format(name), f"salt/cloud/{name}/requesting",
args={ args={
"kwargs": __utils__["cloud.filter_event"]( "kwargs": __utils__["cloud.filter_event"](
"requesting", kwargs, list(kwargs) "requesting", kwargs, list(kwargs)
@ -392,7 +392,7 @@ def create(vm_):
description_elem = ElementTree.Element("description") description_elem = ElementTree.Element("description")
domain_xml.insert(0, description_elem) domain_xml.insert(0, description_elem)
description = domain_xml.find("./description") description = domain_xml.find("./description")
description.text = "Cloned from {}".format(base) description.text = f"Cloned from {base}"
domain_xml.remove(domain_xml.find("./uuid")) domain_xml.remove(domain_xml.find("./uuid"))
for iface_xml in domain_xml.findall("./devices/interface"): for iface_xml in domain_xml.findall("./devices/interface"):
@ -426,9 +426,7 @@ def create(vm_):
# see if there is a path element that needs rewriting # see if there is a path element that needs rewriting
if source_element and "path" in source_element.attrib: if source_element and "path" in source_element.attrib:
path = source_element.attrib["path"] path = source_element.attrib["path"]
new_path = path.replace( new_path = path.replace(f"/domain-{base}/", f"/domain-{name}/")
"/domain-{}/".format(base), "/domain-{}/".format(name)
)
log.debug("Rewriting agent socket path to %s", new_path) log.debug("Rewriting agent socket path to %s", new_path)
source_element.attrib["path"] = new_path source_element.attrib["path"] = new_path
@ -471,7 +469,7 @@ def create(vm_):
disk.find("./source").attrib["file"] = new_volume.path() disk.find("./source").attrib["file"] = new_volume.path()
else: else:
raise SaltCloudExecutionFailure( raise SaltCloudExecutionFailure(
"Disk type '{}' not supported".format(disk_type) f"Disk type '{disk_type}' not supported"
) )
clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml)) clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
@ -515,7 +513,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"created instance", "created instance",
"salt/cloud/{}/created".format(name), f"salt/cloud/{name}/created",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"created", vm_, ["name", "profile", "provider", "driver"] "created", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -617,15 +615,15 @@ def destroy(name, call=None):
pass pass
if not found: if not found:
return "{} doesn't exist and can't be deleted".format(name) return f"{name} doesn't exist and can't be deleted"
if len(found) > 1: if len(found) > 1:
return "{} doesn't identify a unique machine leaving things".format(name) return f"{name} doesn't identify a unique machine leaving things"
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -636,7 +634,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -718,15 +716,15 @@ def find_pool_and_volume(conn, path):
for v in sp.listAllVolumes(): for v in sp.listAllVolumes():
if v.path() == path: if v.path() == path:
return sp, v return sp, v
raise SaltCloudNotFound("Could not find volume for path {}".format(path)) raise SaltCloudNotFound(f"Could not find volume for path {path}")
def generate_new_name(orig_name): def generate_new_name(orig_name):
if "." not in orig_name: if "." not in orig_name:
return "{}-{}".format(orig_name, uuid.uuid1()) return f"{orig_name}-{uuid.uuid1()}"
name, ext = orig_name.rsplit(".", 1) name, ext = orig_name.rsplit(".", 1)
return "{}-{}.{}".format(name, uuid.uuid1(), ext) return f"{name}-{uuid.uuid1()}.{ext}"
def get_domain_volumes(conn, domain): def get_domain_volumes(conn, domain):

View file

@ -179,7 +179,7 @@ def _salt(fun, *args, **kw):
ping_retries += 1 ping_retries += 1
log.error("%s unreachable, retrying", target) log.error("%s unreachable, retrying", target)
if not ping: if not ping:
raise SaltCloudSystemExit("Target {} unreachable".format(target)) raise SaltCloudSystemExit(f"Target {target} unreachable")
jid = conn.cmd_async(tgt=target, fun=fun, arg=args, kwarg=kw, **rkwargs) jid = conn.cmd_async(tgt=target, fun=fun, arg=args, kwarg=kw, **rkwargs)
cret = conn.cmd( cret = conn.cmd(
tgt=target, fun="saltutil.find_job", arg=[jid], timeout=10, **kwargs tgt=target, fun="saltutil.find_job", arg=[jid], timeout=10, **kwargs
@ -224,9 +224,7 @@ def _salt(fun, *args, **kw):
time.sleep(0.5) time.sleep(0.5)
try: try:
if "is not available." in ret: if "is not available." in ret:
raise SaltCloudSystemExit( raise SaltCloudSystemExit(f"module/function {fun} is not available")
"module/function {} is not available".format(fun)
)
except SaltCloudSystemExit: # pylint: disable=try-except-raise except SaltCloudSystemExit: # pylint: disable=try-except-raise
raise raise
except TypeError: except TypeError:
@ -367,12 +365,12 @@ def destroy(vm_, call=None):
) )
if not get_configured_provider(): if not get_configured_provider():
return return
ret = {"comment": "{} was not found".format(vm_), "result": False} ret = {"comment": f"{vm_} was not found", "result": False}
if _salt("lxc.info", vm_, path=path): if _salt("lxc.info", vm_, path=path):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(vm_), f"salt/cloud/{vm_}/destroying",
args={"name": vm_, "instance_id": vm_}, args={"name": vm_, "instance_id": vm_},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -380,11 +378,11 @@ def destroy(vm_, call=None):
cret = _salt("lxc.destroy", vm_, stop=True, path=path) cret = _salt("lxc.destroy", vm_, stop=True, path=path)
ret["result"] = cret["result"] ret["result"] = cret["result"]
if ret["result"]: if ret["result"]:
ret["comment"] = "{} was destroyed".format(vm_) ret["comment"] = f"{vm_} was destroyed"
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(vm_), f"salt/cloud/{vm_}/destroyed",
args={"name": vm_, "instance_id": vm_}, args={"name": vm_, "instance_id": vm_},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -506,14 +504,14 @@ def get_configured_provider(vm_=None):
matched = False matched = False
# --list-images level # --list-images level
if img_provider: if img_provider:
tgt = "provider: {}".format(img_provider) tgt = f"provider: {img_provider}"
if dalias == img_provider: if dalias == img_provider:
data = get_provider(img_provider) data = get_provider(img_provider)
matched = True matched = True
# providers are set in configuration # providers are set in configuration
if not data and "profile" not in __opts__ and arg_providers: if not data and "profile" not in __opts__ and arg_providers:
for name in arg_providers: for name in arg_providers:
tgt = "provider: {}".format(name) tgt = f"provider: {name}"
if dalias == name: if dalias == name:
data = get_provider(name) data = get_provider(name)
if data: if data:
@ -523,13 +521,13 @@ def get_configured_provider(vm_=None):
elif "profile" in __opts__: elif "profile" in __opts__:
curprof = __opts__["profile"] curprof = __opts__["profile"]
profs = __opts__["profiles"] profs = __opts__["profiles"]
tgt = "profile: {}".format(curprof) tgt = f"profile: {curprof}"
if ( if (
curprof in profs curprof in profs
and profs[curprof]["provider"] == _get_active_provider_name() and profs[curprof]["provider"] == _get_active_provider_name()
): ):
prov, cdriver = profs[curprof]["provider"].split(":") prov, cdriver = profs[curprof]["provider"].split(":")
tgt += " provider: {}".format(prov) tgt += f" provider: {prov}"
data = get_provider(prov) data = get_provider(prov)
matched = True matched = True
# fallback if we have only __active_provider_name__ # fallback if we have only __active_provider_name__

View file

@ -193,9 +193,7 @@ def get_size(vm_):
if size: if size:
return size return size
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.")
"The specified size, '{}', could not be found.".format(vm_size)
)
def get_image(vm_): def get_image(vm_):
@ -211,9 +209,7 @@ def get_image(vm_):
if vm_image and vm_image in (images[key]["id"], images[key]["name"]): if vm_image and vm_image in (images[key]["id"], images[key]["name"]):
return images[key] return images[key]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.")
"The specified image, '{}', could not be found.".format(vm_image)
)
def avail_locations(conn=None, call=None): def avail_locations(conn=None, call=None):
@ -735,7 +731,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -749,7 +745,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -846,7 +842,7 @@ def get_key_filename(vm_):
key_filename = os.path.expanduser(key_filename) key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename): if not os.path.isfile(key_filename):
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The defined ssh_private_key '{}' does not exist".format(key_filename) f"The defined ssh_private_key '{key_filename}' does not exist"
) )
return key_filename return key_filename
@ -897,11 +893,9 @@ def _wait_for_completion(conn, wait_timeout, server_id):
if server_state == "powered_on": if server_state == "powered_on":
return return
elif server_state == "failed": elif server_state == "failed":
raise Exception("Server creation failed for {}".format(server_id)) raise Exception(f"Server creation failed for {server_id}")
elif server_state in ("active", "enabled", "deploying", "configuring"): elif server_state in ("active", "enabled", "deploying", "configuring"):
continue continue
else: else:
raise Exception("Unknown server state {}".format(server_state)) raise Exception(f"Unknown server state {server_state}")
raise Exception( raise Exception(f"Timed out waiting for server create completion for {server_id}")
"Timed out waiting for server create completion for {}".format(server_id)
)

View file

@ -76,7 +76,7 @@ from salt.exceptions import (
) )
try: try:
import xmlrpc.client import xmlrpc.client # nosec
from lxml import etree from lxml import etree
@ -85,7 +85,6 @@ except ImportError:
HAS_XML_LIBS = False HAS_XML_LIBS = False
# Get Logging Started
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
__virtualname__ = "opennebula" __virtualname__ = "opennebula"
@ -558,7 +557,7 @@ def get_cluster_id(kwargs=None, call=None):
try: try:
ret = list_clusters()[name]["id"] ret = list_clusters()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit("The cluster '{}' could not be found".format(name)) raise SaltCloudSystemExit(f"The cluster '{name}' could not be found")
return ret return ret
@ -590,7 +589,7 @@ def get_datastore_id(kwargs=None, call=None):
try: try:
ret = list_datastores()[name]["id"] ret = list_datastores()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit("The datastore '{}' could not be found.".format(name)) raise SaltCloudSystemExit(f"The datastore '{name}' could not be found.")
return ret return ret
@ -622,7 +621,7 @@ def get_host_id(kwargs=None, call=None):
try: try:
ret = avail_locations()[name]["id"] ret = avail_locations()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit("The host '{}' could not be found".format(name)) raise SaltCloudSystemExit(f"The host '{name}' could not be found")
return ret return ret
@ -641,9 +640,7 @@ def get_image(vm_):
for image in images: for image in images:
if vm_image in (images[image]["name"], images[image]["id"]): if vm_image in (images[image]["name"], images[image]["id"]):
return images[image]["id"] return images[image]["id"]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.")
"The specified image, '{}', could not be found.".format(vm_image)
)
def get_image_id(kwargs=None, call=None): def get_image_id(kwargs=None, call=None):
@ -673,7 +670,7 @@ def get_image_id(kwargs=None, call=None):
try: try:
ret = avail_images()[name]["id"] ret = avail_images()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit("The image '{}' could not be found".format(name)) raise SaltCloudSystemExit(f"The image '{name}' could not be found")
return ret return ret
@ -697,7 +694,7 @@ def get_location(vm_):
if vm_location in (locations[location]["name"], locations[location]["id"]): if vm_location in (locations[location]["name"], locations[location]["id"]):
return locations[location]["id"] return locations[location]["id"]
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified location, '{}', could not be found.".format(vm_location) f"The specified location, '{vm_location}', could not be found."
) )
@ -728,9 +725,7 @@ def get_secgroup_id(kwargs=None, call=None):
try: try:
ret = list_security_groups()[name]["id"] ret = list_security_groups()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit( raise SaltCloudSystemExit(f"The security group '{name}' could not be found.")
"The security group '{}' could not be found.".format(name)
)
return ret return ret
@ -761,7 +756,7 @@ def get_template_image(kwargs=None, call=None):
ret = list_templates()[name]["template"]["disk"]["image"] ret = list_templates()[name]["template"]["disk"]["image"]
except KeyError: except KeyError:
raise SaltCloudSystemExit( raise SaltCloudSystemExit(
"The image for template '{}' could not be found.".format(name) f"The image for template '{name}' could not be found."
) )
return ret return ret
@ -794,7 +789,7 @@ def get_template_id(kwargs=None, call=None):
try: try:
ret = list_templates()[name]["id"] ret = list_templates()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit("The template '{}' could not be found.".format(name)) raise SaltCloudSystemExit(f"The template '{name}' could not be found.")
return ret return ret
@ -816,7 +811,7 @@ def get_template(vm_):
return list_templates()[vm_template]["id"] return list_templates()[vm_template]["id"]
except KeyError: except KeyError:
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified template, '{}', could not be found.".format(vm_template) f"The specified template, '{vm_template}', could not be found."
) )
@ -847,7 +842,7 @@ def get_vm_id(kwargs=None, call=None):
try: try:
ret = list_nodes()[name]["id"] ret = list_nodes()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit("The VM '{}' could not be found.".format(name)) raise SaltCloudSystemExit(f"The VM '{name}' could not be found.")
return ret return ret
@ -879,7 +874,7 @@ def get_vn_id(kwargs=None, call=None):
try: try:
ret = list_vns()[name]["id"] ret = list_vns()[name]["id"]
except KeyError: except KeyError:
raise SaltCloudSystemExit("The VN '{}' could not be found.".format(name)) raise SaltCloudSystemExit(f"The VN '{name}' could not be found.")
return ret return ret
@ -895,9 +890,7 @@ def _get_device_template(disk, disk_info, template=None):
def _require_disk_opts(*args): def _require_disk_opts(*args):
for arg in args: for arg in args:
if arg not in disk_info: if arg not in disk_info:
raise SaltCloudSystemExit( raise SaltCloudSystemExit(f"The disk {disk} requires a {arg} argument")
"The disk {} requires a {} argument".format(disk, arg)
)
_require_disk_opts("disk_type", "size") _require_disk_opts("disk_type", "size")
@ -919,12 +912,12 @@ def _get_device_template(disk, disk_info, template=None):
if disk_type == "volatile": if disk_type == "volatile":
_require_disk_opts("type") _require_disk_opts("type")
v_type = disk_info["type"] v_type = disk_info["type"]
temp = "DISK=[TYPE={}, SIZE={}]".format(v_type, size) temp = f"DISK=[TYPE={v_type}, SIZE={size}]"
if v_type == "fs": if v_type == "fs":
_require_disk_opts("format") _require_disk_opts("format")
format = disk_info["format"] format = disk_info["format"]
temp = "DISK=[TYPE={}, SIZE={}, FORMAT={}]".format(v_type, size, format) temp = f"DISK=[TYPE={v_type}, SIZE={size}, FORMAT={format}]"
return temp return temp
# TODO add persistant disk_type # TODO add persistant disk_type
@ -1101,7 +1094,7 @@ def create(vm_):
) )
if key_filename is not None and not os.path.isfile(key_filename): if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The defined key_filename '{}' does not exist".format(key_filename) f"The defined key_filename '{key_filename}' does not exist"
) )
if fqdn: if fqdn:
@ -1178,7 +1171,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
) )
@ -1192,7 +1185,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
) )
@ -4474,7 +4467,7 @@ def _get_xml(xml_str):
except etree.XMLSyntaxError as err: except etree.XMLSyntaxError as err:
# opennebula returned invalid XML, which could be an error message, so # opennebula returned invalid XML, which could be an error message, so
# log it # log it
raise SaltCloudSystemExit("opennebula returned: {}".format(xml_str)) raise SaltCloudSystemExit(f"opennebula returned: {xml_str}")
return xml_data return xml_data

View file

@ -737,7 +737,7 @@ def create(vm_):
) )
if key_filename is not None and not os.path.isfile(key_filename): if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The defined ssh_key_file '{}' does not exist".format(key_filename) f"The defined ssh_key_file '{key_filename}' does not exist"
) )
vm_["key_filename"] = key_filename vm_["key_filename"] = key_filename
@ -846,7 +846,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -863,7 +863,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -242,9 +242,7 @@ def _wait_for_status(status_type, object_id, status=None, timeout=500, quiet=Tru
manager = packet.Manager(auth_token=vm_["token"]) manager = packet.Manager(auth_token=vm_["token"])
for i in range(0, iterations): for i in range(0, iterations):
get_object = getattr( get_object = getattr(manager, f"get_{status_type}")
manager, "get_{status_type}".format(status_type=status_type)
)
obj = get_object(object_id) obj = get_object(object_id)
if obj.state == status: if obj.state == status:
@ -340,7 +338,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"starting create", "starting create",
"salt/cloud/{}/creating".format(name), f"salt/cloud/{name}/creating",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"creating", vm_, ["name", "profile", "provider", "driver"] "creating", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -413,7 +411,7 @@ def create(vm_):
volume = manager.create_volume( volume = manager.create_volume(
vm_["project_id"], vm_["project_id"],
"{}_storage".format(name), f"{name}_storage",
vm_.get("storage_tier"), vm_.get("storage_tier"),
vm_.get("storage_size"), vm_.get("storage_size"),
vm_.get("location"), vm_.get("location"),
@ -441,7 +439,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"created instance", "created instance",
"salt/cloud/{}/created".format(name), f"salt/cloud/{name}/created",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"created", vm_, ["name", "profile", "provider", "driver"] "created", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -580,7 +578,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -606,7 +604,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -310,11 +310,11 @@ def create(vm_):
name = vm_["name"] name = vm_["name"]
if not wait_until(name, "CREATED"): if not wait_until(name, "CREATED"):
return {"Error": "Unable to start {}, command timed out".format(name)} return {"Error": f"Unable to start {name}, command timed out"}
start(vm_["name"], call="action") start(vm_["name"], call="action")
if not wait_until(name, "STARTED"): if not wait_until(name, "STARTED"):
return {"Error": "Unable to start {}, command timed out".format(name)} return {"Error": f"Unable to start {name}, command timed out"}
def __query_node_data(vm_name): def __query_node_data(vm_name):
data = show_instance(vm_name, call="action") data = show_instance(vm_name, call="action")
@ -391,7 +391,7 @@ def query(action=None, command=None, args=None, method="GET", data=None):
path += action path += action
if command: if command:
path += "/{}".format(command) path += f"/{command}"
if not type(args, dict): if not type(args, dict):
args = {} args = {}
@ -404,7 +404,7 @@ def query(action=None, command=None, args=None, method="GET", data=None):
if args: if args:
params = urllib.parse.urlencode(args) params = urllib.parse.urlencode(args)
req = urllib.request.Request(url="{}?{}".format(path, params), **kwargs) req = urllib.request.Request(url=f"{path}?{params}", **kwargs)
else: else:
req = urllib.request.Request(url=path, **kwargs) req = urllib.request.Request(url=path, **kwargs)
@ -526,7 +526,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -536,7 +536,7 @@ def destroy(name, call=None):
if node["state"] == "STARTED": if node["state"] == "STARTED":
stop(name, call="action") stop(name, call="action")
if not wait_until(name, "STOPPED"): if not wait_until(name, "STOPPED"):
return {"Error": "Unable to destroy {}, command timed out".format(name)} return {"Error": f"Unable to destroy {name}, command timed out"}
data = query(action="ve", command=name, method="DELETE") data = query(action="ve", command=name, method="DELETE")
@ -546,7 +546,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -557,7 +557,7 @@ def destroy(name, call=None):
name, _get_active_provider_name().split(":")[0], __opts__ name, _get_active_provider_name().split(":")[0], __opts__
) )
return {"Destroyed": "{} was destroyed.".format(name)} return {"Destroyed": f"{name} was destroyed."}
def start(name, call=None): def start(name, call=None):
@ -575,12 +575,12 @@ def start(name, call=None):
"The show_instance action must be called with -a or --action." "The show_instance action must be called with -a or --action."
) )
data = query(action="ve", command="{}/start".format(name), method="PUT") data = query(action="ve", command=f"{name}/start", method="PUT")
if "error" in data: if "error" in data:
return data["error"] return data["error"]
return {"Started": "{} was started.".format(name)} return {"Started": f"{name} was started."}
def stop(name, call=None): def stop(name, call=None):
@ -598,9 +598,9 @@ def stop(name, call=None):
"The show_instance action must be called with -a or --action." "The show_instance action must be called with -a or --action."
) )
data = query(action="ve", command="{}/stop".format(name), method="PUT") data = query(action="ve", command=f"{name}/stop", method="PUT")
if "error" in data: if "error" in data:
return data["error"] return data["error"]
return {"Stopped": "{} was stopped.".format(name)} return {"Stopped": f"{name} was stopped."}

View file

@ -328,9 +328,7 @@ def get_size(vm_):
combinations = (str(sizes[size]["id"]), str(size)) combinations = (str(sizes[size]["id"]), str(size))
if vm_size and str(vm_size) in combinations: if vm_size and str(vm_size) in combinations:
return sizes[size] return sizes[size]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.")
"The specified size, '{}', could not be found.".format(vm_size)
)
def get_datacenter_id(): def get_datacenter_id():
@ -415,7 +413,7 @@ def get_datacenter(conn):
return item return item
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified datacenter '{}' could not be found.".format(datacenter_id) f"The specified datacenter '{datacenter_id}' could not be found."
) )
@ -488,9 +486,7 @@ def get_image(vm_):
if vm_image and vm_image in (images[key]["id"], images[key]["name"]): if vm_image and vm_image in (images[key]["id"], images[key]["name"]):
return images[key] return images[key]
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.")
"The specified image, '{}', could not be found.".format(vm_image)
)
def list_datacenters(conn=None, call=None): def list_datacenters(conn=None, call=None):
@ -725,7 +721,7 @@ def get_public_keys(vm_):
key_filename = os.path.expanduser(key_filename) key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename): if not os.path.isfile(key_filename):
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The defined ssh_public_key '{}' does not exist".format(key_filename) f"The defined ssh_public_key '{key_filename}' does not exist"
) )
ssh_keys = [] ssh_keys = []
with salt.utils.files.fopen(key_filename) as rfh: with salt.utils.files.fopen(key_filename) as rfh:
@ -746,7 +742,7 @@ def get_key_filename(vm_):
key_filename = os.path.expanduser(key_filename) key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename): if not os.path.isfile(key_filename):
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The defined ssh_private_key '{}' does not exist".format(key_filename) f"The defined ssh_private_key '{key_filename}' does not exist"
) )
return key_filename return key_filename
@ -941,7 +937,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -972,7 +968,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -1142,9 +1138,7 @@ def _get_data_volumes(vm_):
# Verify the required 'disk_size' property is present in the cloud # Verify the required 'disk_size' property is present in the cloud
# profile config # profile config
if "disk_size" not in volumes[key].keys(): if "disk_size" not in volumes[key].keys():
raise SaltCloudConfigError( raise SaltCloudConfigError(f"The volume '{key}' is missing 'disk_size'")
"The volume '{}' is missing 'disk_size'".format(key)
)
# Use 'HDD' if no 'disk_type' property is present in cloud profile # Use 'HDD' if no 'disk_type' property is present in cloud profile
if "disk_type" not in volumes[key].keys(): if "disk_type" not in volumes[key].keys():
volumes[key]["disk_type"] = "HDD" volumes[key]["disk_type"] = "HDD"
@ -1187,7 +1181,7 @@ def _get_firewall_rules(firewall_rules):
# profile config # profile config
if "protocol" not in firewall_rules[key].keys(): if "protocol" not in firewall_rules[key].keys():
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The firewall rule '{}' is missing 'protocol'".format(key) f"The firewall rule '{key}' is missing 'protocol'"
) )
ret.append( ret.append(
FirewallRule( FirewallRule(

View file

@ -108,7 +108,7 @@ def _compute_signature(parameters, access_key_secret, method, path):
""" """
parameters["signature_method"] = "HmacSHA256" parameters["signature_method"] = "HmacSHA256"
string_to_sign = "{}\n{}\n".format(method.upper(), path) string_to_sign = f"{method.upper()}\n{path}\n"
keys = sorted(parameters.keys()) keys = sorted(parameters.keys())
pairs = [] pairs = []
@ -166,9 +166,9 @@ def query(params=None):
for sk, sv in value[i - 1].items(): for sk, sv in value[i - 1].items():
if isinstance(sv, dict) or isinstance(sv, list): if isinstance(sv, dict) or isinstance(sv, list):
sv = salt.utils.json.dumps(sv, separators=(",", ":")) sv = salt.utils.json.dumps(sv, separators=(",", ":"))
real_parameters["{}.{}.{}".format(key, i, sk)] = sv real_parameters[f"{key}.{i}.{sk}"] = sv
else: else:
real_parameters["{}.{}".format(key, i)] = value[i - 1] real_parameters[f"{key}.{i}"] = value[i - 1]
else: else:
real_parameters[key] = value real_parameters[key] = value
@ -252,7 +252,7 @@ def _get_location(vm_=None):
return vm_location return vm_location
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified location, '{}', could not be found.".format(vm_location) f"The specified location, '{vm_location}', could not be found."
) )
@ -320,9 +320,7 @@ def _get_image(vm_):
if vm_image in images: if vm_image in images:
return vm_image return vm_image
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.")
"The specified image, '{}', could not be found.".format(vm_image)
)
def show_image(kwargs, call=None): def show_image(kwargs, call=None):
@ -442,9 +440,7 @@ def _get_size(vm_):
if vm_size in sizes.keys(): if vm_size in sizes.keys():
return vm_size return vm_size
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.")
"The specified size, '{}', could not be found.".format(vm_size)
)
def _show_normalized_node(full_node): def _show_normalized_node(full_node):
@ -626,7 +622,7 @@ def show_instance(instance_id, call=None, kwargs=None):
if items["total_count"] == 0: if items["total_count"] == 0:
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified instance, '{}', could not be found.".format(instance_id) f"The specified instance, '{instance_id}', could not be found."
) )
full_node = items["instance_set"][0] full_node = items["instance_set"][0]
@ -878,7 +874,7 @@ def destroy(instance_id, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -894,7 +890,7 @@ def destroy(instance_id, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -289,7 +289,7 @@ def create(vm_):
if ssh_host: if ssh_host:
log.info("trying to ping %s", ssh_host) log.info("trying to ping %s", ssh_host)
count = "n" if salt.utils.platform.is_windows() else "c" count = "n" if salt.utils.platform.is_windows() else "c"
cmd = "ping -{} 1 {}".format(count, ssh_host) cmd = f"ping -{count} 1 {ssh_host}"
good_ping = local.cmd(wol_host, "cmd.retcode", [cmd]) == 0 good_ping = local.cmd(wol_host, "cmd.retcode", [cmd]) == 0
if good_ping: if good_ping:
log.info("successful ping.") log.info("successful ping.")
@ -358,7 +358,7 @@ def _verify(vm_):
log.debug("Testing SMB protocol for %s", vm_["name"]) log.debug("Testing SMB protocol for %s", vm_["name"])
if __utils__["smb.get_conn"](**kwargs) is False: if __utils__["smb.get_conn"](**kwargs) is False:
return False return False
except (smbSessionError) as exc: except smbSessionError as exc:
log.error("Exception: %s", exc) log.error("Exception: %s", exc)
return False return False
@ -464,7 +464,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=opts["sock_dir"], sock_dir=opts["sock_dir"],
transport=opts["transport"], transport=opts["transport"],
@ -510,13 +510,13 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=opts["sock_dir"], sock_dir=opts["sock_dir"],
transport=opts["transport"], transport=opts["transport"],
) )
return {"Destroyed": "{} was destroyed.".format(name)} return {"Destroyed": f"{name} was destroyed."}
def reboot(name, call=None): def reboot(name, call=None):

View file

@ -160,7 +160,7 @@ def get_image(server_):
if server_image in (images[image]["name"], images[image]["id"]): if server_image in (images[image]["name"], images[image]["id"]):
return images[image]["id"] return images[image]["id"]
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified image, '{}', could not be found.".format(server_image) f"The specified image, '{server_image}', could not be found."
) )
@ -225,7 +225,7 @@ def create(server_):
if key_filename is not None and not os.path.isfile(key_filename): if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError( raise SaltCloudConfigError(
"The defined key_filename '{}' does not exist".format(key_filename) f"The defined key_filename '{key_filename}' does not exist"
) )
ssh_password = config.get_cloud_config_value("ssh_password", server_, __opts__) ssh_password = config.get_cloud_config_value("ssh_password", server_, __opts__)
@ -346,10 +346,10 @@ def query(
) )
) )
path = "{}/{}/".format(base_path, method) path = f"{base_path}/{method}/"
if server_id: if server_id:
path += "{}/".format(server_id) path += f"{server_id}/"
if command: if command:
path += command path += command
@ -439,7 +439,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -457,7 +457,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -269,7 +269,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"starting create", "starting create",
"salt/cloud/{}/creating".format(name), f"salt/cloud/{name}/creating",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"creating", vm_, ["name", "profile", "provider", "driver"] "creating", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -395,7 +395,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"requesting instance", "requesting instance",
"salt/cloud/{}/requesting".format(name), f"salt/cloud/{name}/requesting",
args={ args={
"kwargs": __utils__["cloud.filter_event"]( "kwargs": __utils__["cloud.filter_event"](
"requesting", kwargs, list(kwargs) "requesting", kwargs, list(kwargs)
@ -513,7 +513,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"created instance", "created instance",
"salt/cloud/{}/created".format(name), f"salt/cloud/{name}/created",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"created", vm_, ["name", "profile", "provider", "driver"] "created", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -620,7 +620,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -633,7 +633,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -241,7 +241,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"starting create", "starting create",
"salt/cloud/{}/creating".format(name), f"salt/cloud/{name}/creating",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"creating", vm_, ["name", "profile", "provider", "driver"] "creating", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -311,7 +311,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"requesting instance", "requesting instance",
"salt/cloud/{}/requesting".format(name), f"salt/cloud/{name}/requesting",
args={ args={
"kwargs": __utils__["cloud.filter_event"]( "kwargs": __utils__["cloud.filter_event"](
"requesting", kwargs, list(kwargs) "requesting", kwargs, list(kwargs)
@ -406,7 +406,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"created instance", "created instance",
"salt/cloud/{}/created".format(name), f"salt/cloud/{name}/created",
args=__utils__["cloud.filter_event"]( args=__utils__["cloud.filter_event"](
"created", vm_, ["name", "profile", "provider", "driver"] "created", vm_, ["name", "profile", "provider", "driver"]
), ),
@ -514,7 +514,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -535,7 +535,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -123,7 +123,7 @@ def get_provider_client(name=None):
elif name == "vpc_client": elif name == "vpc_client":
client = vpc_client.VpcClient(crd, region, cpf) client = vpc_client.VpcClient(crd, region, cpf)
else: else:
raise SaltCloudSystemExit("Client name {} is not supported".format(name)) raise SaltCloudSystemExit(f"Client name {name} is not supported")
return client return client
@ -206,11 +206,11 @@ def avail_sizes(call=None):
ret[typeConfig.InstanceType] = { ret[typeConfig.InstanceType] = {
"Zone": typeConfig.Zone, "Zone": typeConfig.Zone,
"InstanceFamily": typeConfig.InstanceFamily, "InstanceFamily": typeConfig.InstanceFamily,
"Memory": "{}GB".format(typeConfig.Memory), "Memory": f"{typeConfig.Memory}GB",
"CPU": "{}-Core".format(typeConfig.CPU), "CPU": f"{typeConfig.CPU}-Core",
} }
if typeConfig.GPU: if typeConfig.GPU:
ret[typeConfig.InstanceType]["GPU"] = "{}-Core".format(typeConfig.GPU) ret[typeConfig.InstanceType]["GPU"] = f"{typeConfig.GPU}-Core"
return ret return ret
@ -714,7 +714,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -730,7 +730,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -782,9 +782,7 @@ def show_image(kwargs, call=None):
resp = client.DescribeImages(req) resp = client.DescribeImages(req)
if not resp.ImageSet: if not resp.ImageSet:
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image '{image}' could not be found.")
"The specified image '{}' could not be found.".format(image)
)
ret = {} ret = {}
for image in resp.ImageSet: for image in resp.ImageSet:
@ -794,7 +792,7 @@ def show_image(kwargs, call=None):
"ImageSource": image.ImageSource, "ImageSource": image.ImageSource,
"Platform": image.Platform, "Platform": image.Platform,
"Architecture": image.Architecture, "Architecture": image.Architecture,
"ImageSize": "{}GB".format(image.ImageSize), "ImageSize": f"{image.ImageSize}GB",
"ImageState": image.ImageState, "ImageState": image.ImageState,
} }
@ -893,7 +891,7 @@ def _get_node(name):
) )
time.sleep(0.5) time.sleep(0.5)
raise SaltCloudNotFound("Failed to get instance info {}".format(name)) raise SaltCloudNotFound(f"Failed to get instance info {name}")
def _get_nodes(): def _get_nodes():
@ -940,7 +938,7 @@ def _get_images(image_type):
"ImageSource": image.ImageSource, "ImageSource": image.ImageSource,
"Platform": image.Platform, "Platform": image.Platform,
"Architecture": image.Architecture, "Architecture": image.Architecture,
"ImageSize": "{}GB".format(image.ImageSize), "ImageSize": f"{image.ImageSize}GB",
} }
return ret return ret
@ -958,9 +956,7 @@ def __get_image(vm_):
if vm_image in images: if vm_image in images:
return vm_image return vm_image
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image '{vm_image}' could not be found.")
"The specified image '{}' could not be found.".format(vm_image)
)
def __get_size(vm_): def __get_size(vm_):
@ -975,9 +971,7 @@ def __get_size(vm_):
if vm_size in sizes: if vm_size in sizes:
return vm_size return vm_size
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified size '{vm_size}' could not be found.")
"The specified size '{}' could not be found.".format(vm_size)
)
def __get_securitygroups(vm_): def __get_securitygroups(vm_):

View file

@ -256,7 +256,7 @@ def create(vm_):
vm_.setdefault("ssh_port", ret["ssh_port"]) vm_.setdefault("ssh_port", ret["ssh_port"])
except (KeyError, TypeError): except (KeyError, TypeError):
raise SaltInvocationError( raise SaltInvocationError(
"Insufficient SSH addressing information for {}".format(name) f"Insufficient SSH addressing information for {name}"
) )
log.info( log.info(
@ -300,7 +300,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=opts["sock_dir"], sock_dir=opts["sock_dir"],
transport=opts["transport"], transport=opts["transport"],
@ -317,7 +317,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=opts["sock_dir"], sock_dir=opts["sock_dir"],
transport=opts["transport"], transport=opts["transport"],
@ -328,11 +328,11 @@ def destroy(name, call=None):
name, _get_active_provider_name().split(":")[0], opts name, _get_active_provider_name().split(":")[0], opts
) )
return {"Destroyed": "{} was destroyed.".format(name)} return {"Destroyed": f"{name} was destroyed."}
else: else:
return {"Error": "Error destroying {}".format(name)} return {"Error": f"Error destroying {name}"}
else: else:
return {"Error": "No response from {}. Cannot destroy.".format(name)} return {"Error": f"No response from {name}. Cannot destroy."}
# noinspection PyTypeChecker # noinspection PyTypeChecker

View file

@ -368,12 +368,12 @@ def destroy(name, call=None):
""" """
log.info("Attempting to delete instance %s", name) log.info("Attempting to delete instance %s", name)
if not vb_machine_exists(name): if not vb_machine_exists(name):
return "{} doesn't exist and can't be deleted".format(name) return f"{name} doesn't exist and can't be deleted"
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -384,7 +384,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -306,7 +306,7 @@ def _add_new_hard_disk_helper(
disk_spec.device.key = random_key disk_spec.device.key = random_key
disk_spec.device.deviceInfo = vim.Description() disk_spec.device.deviceInfo = vim.Description()
disk_spec.device.deviceInfo.label = disk_label disk_spec.device.deviceInfo.label = disk_label
disk_spec.device.deviceInfo.summary = "{} GB".format(size_gb) disk_spec.device.deviceInfo.summary = f"{size_gb} GB"
disk_spec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo() disk_spec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
disk_spec.device.backing.thinProvisioned = thin_provision disk_spec.device.backing.thinProvisioned = thin_provision
@ -662,7 +662,7 @@ def _set_cd_or_dvd_backing_type(drive, device_type, mode, iso_path):
if datastore_ref: if datastore_ref:
drive.backing.datastore = datastore_ref drive.backing.datastore = datastore_ref
drive.deviceInfo.summary = "ISO {}".format(iso_path) drive.deviceInfo.summary = f"ISO {iso_path}"
elif device_type == "client_device": elif device_type == "client_device":
if mode == "passthrough": if mode == "passthrough":
@ -917,7 +917,7 @@ def _manage_devices(devices, vm=None, container_ref=None, new_vm_name=None):
else None else None
) )
if bus_sharing and bus_sharing in ["virtual", "physical", "no"]: if bus_sharing and bus_sharing in ["virtual", "physical", "no"]:
bus_sharing = "{}Sharing".format(bus_sharing) bus_sharing = f"{bus_sharing}Sharing"
if bus_sharing != device.sharedBus: if bus_sharing != device.sharedBus:
# Only edit the SCSI controller if bus_sharing is different # Only edit the SCSI controller if bus_sharing is different
scsi_spec = _edit_existing_scsi_controller( scsi_spec = _edit_existing_scsi_controller(
@ -1327,7 +1327,7 @@ def _format_instance_info_select(vm, selection):
if "size" in selection: if "size" in selection:
cpu = defaultto(vm, "config.hardware.numCPU") cpu = defaultto(vm, "config.hardware.numCPU")
ram = "{} MB".format(defaultto(vm, "config.hardware.memoryMB")) ram = "{} MB".format(defaultto(vm, "config.hardware.memoryMB"))
vm_select_info["size"] = "cpu: {}\nram: {}".format(cpu, ram) vm_select_info["size"] = f"cpu: {cpu}\nram: {ram}"
vm_select_info["size_dict"] = { vm_select_info["size_dict"] = {
"cpu": cpu, "cpu": cpu,
"memory": ram, "memory": ram,
@ -1454,15 +1454,21 @@ def _format_instance_info_select(vm, selection):
if "storage" in selection: if "storage" in selection:
storage_full_info = { storage_full_info = {
"committed": int(vm["summary.storage.committed"]) "committed": (
if "summary.storage.committed" in vm int(vm["summary.storage.committed"])
else "N/A", if "summary.storage.committed" in vm
"uncommitted": int(vm["summary.storage.uncommitted"]) else "N/A"
if "summary.storage.uncommitted" in vm ),
else "N/A", "uncommitted": (
"unshared": int(vm["summary.storage.unshared"]) int(vm["summary.storage.uncommitted"])
if "summary.storage.unshared" in vm if "summary.storage.uncommitted" in vm
else "N/A", else "N/A"
),
"unshared": (
int(vm["summary.storage.unshared"])
if "summary.storage.unshared" in vm
else "N/A"
),
} }
vm_select_info["storage"] = storage_full_info vm_select_info["storage"] = storage_full_info
@ -1553,15 +1559,21 @@ def _format_instance_info(vm):
] = device.backing.fileName ] = device.backing.fileName
storage_full_info = { storage_full_info = {
"committed": int(vm["summary.storage.committed"]) "committed": (
if "summary.storage.committed" in vm int(vm["summary.storage.committed"])
else "N/A", if "summary.storage.committed" in vm
"uncommitted": int(vm["summary.storage.uncommitted"]) else "N/A"
if "summary.storage.uncommitted" in vm ),
else "N/A", "uncommitted": (
"unshared": int(vm["summary.storage.unshared"]) int(vm["summary.storage.uncommitted"])
if "summary.storage.unshared" in vm if "summary.storage.uncommitted" in vm
else "N/A", else "N/A"
),
"unshared": (
int(vm["summary.storage.unshared"])
if "summary.storage.unshared" in vm
else "N/A"
),
} }
file_full_info = {} file_full_info = {}
@ -1593,14 +1605,18 @@ def _format_instance_info(vm):
) )
vm_full_info = { vm_full_info = {
"id": str(vm["name"]), "id": str(vm["name"]),
"image": "{} (Detected)".format(vm["config.guestFullName"]) "image": (
if "config.guestFullName" in vm "{} (Detected)".format(vm["config.guestFullName"])
else "N/A", if "config.guestFullName" in vm
"size": "cpu: {}\nram: {}".format(cpu, ram), else "N/A"
),
"size": f"cpu: {cpu}\nram: {ram}",
"size_dict": {"cpu": cpu, "memory": ram}, "size_dict": {"cpu": cpu, "memory": ram},
"state": str(vm["summary.runtime.powerState"]) "state": (
if "summary.runtime.powerState" in vm str(vm["summary.runtime.powerState"])
else "N/A", if "summary.runtime.powerState" in vm
else "N/A"
),
"private_ips": ip_addresses, "private_ips": ip_addresses,
"public_ips": [], "public_ips": [],
"devices": device_full_info, "devices": device_full_info,
@ -1610,12 +1626,14 @@ def _format_instance_info(vm):
"hostname": str(vm["object"].guest.hostName), "hostname": str(vm["object"].guest.hostName),
"mac_addresses": device_mac_addresses, "mac_addresses": device_mac_addresses,
"networks": network_full_info, "networks": network_full_info,
"path": str(vm["config.files.vmPathName"]) "path": (
if "config.files.vmPathName" in vm str(vm["config.files.vmPathName"])
else "N/A", if "config.files.vmPathName" in vm
"tools_status": str(vm["guest.toolsStatus"]) else "N/A"
if "guest.toolsStatus" in vm ),
else "N/A", "tools_status": (
str(vm["guest.toolsStatus"]) if "guest.toolsStatus" in vm else "N/A"
),
} }
return vm_full_info return vm_full_info
@ -1624,7 +1642,7 @@ def _format_instance_info(vm):
def _get_snapshots(snapshot_list, current_snapshot=None, parent_snapshot_path=""): def _get_snapshots(snapshot_list, current_snapshot=None, parent_snapshot_path=""):
snapshots = {} snapshots = {}
for snapshot in snapshot_list: for snapshot in snapshot_list:
snapshot_path = "{}/{}".format(parent_snapshot_path, snapshot.name) snapshot_path = f"{parent_snapshot_path}/{snapshot.name}"
snapshots[snapshot_path] = { snapshots[snapshot_path] = {
"name": snapshot.name, "name": snapshot.name,
"description": snapshot.description, "description": snapshot.description,
@ -1759,7 +1777,7 @@ def test_vcenter_connection(kwargs=None, call=None):
# Get the service instance object # Get the service instance object
_get_si() _get_si()
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
return "failed to connect: {}".format(exc) return f"failed to connect: {exc}"
return "connection successful" return "connection successful"
@ -2004,14 +2022,18 @@ def list_nodes(kwargs=None, call=None):
) )
vm_info = { vm_info = {
"id": vm["name"], "id": vm["name"],
"image": "{} (Detected)".format(vm["config.guestFullName"]) "image": (
if "config.guestFullName" in vm "{} (Detected)".format(vm["config.guestFullName"])
else "N/A", if "config.guestFullName" in vm
"size": "cpu: {}\nram: {}".format(cpu, ram), else "N/A"
),
"size": f"cpu: {cpu}\nram: {ram}",
"size_dict": {"cpu": cpu, "memory": ram}, "size_dict": {"cpu": cpu, "memory": ram},
"state": str(vm["summary.runtime.powerState"]) "state": (
if "summary.runtime.powerState" in vm str(vm["summary.runtime.powerState"])
else "N/A", if "summary.runtime.powerState" in vm
else "N/A"
),
"private_ips": [vm["guest.ipAddress"]] if "guest.ipAddress" in vm else [], "private_ips": [vm["guest.ipAddress"]] if "guest.ipAddress" in vm else [],
"public_ips": [], "public_ips": [],
} }
@ -2242,15 +2264,21 @@ def avail_images(call=None):
if "config.template" in vm and vm["config.template"]: if "config.template" in vm and vm["config.template"]:
templates[vm["name"]] = { templates[vm["name"]] = {
"name": vm["name"], "name": vm["name"],
"guest_fullname": vm["config.guestFullName"] "guest_fullname": (
if "config.guestFullName" in vm vm["config.guestFullName"]
else "N/A", if "config.guestFullName" in vm
"cpus": vm["config.hardware.numCPU"] else "N/A"
if "config.hardware.numCPU" in vm ),
else "N/A", "cpus": (
"ram": vm["config.hardware.memoryMB"] vm["config.hardware.numCPU"]
if "config.hardware.memoryMB" in vm if "config.hardware.numCPU" in vm
else "N/A", else "N/A"
),
"ram": (
vm["config.hardware.memoryMB"]
if "config.hardware.memoryMB" in vm
else "N/A"
),
} }
return templates return templates
@ -2656,7 +2684,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -2702,7 +2730,7 @@ def destroy(name, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -3107,7 +3135,7 @@ def create(vm_):
) )
if not datastore_ref: if not datastore_ref:
raise SaltCloudSystemExit( raise SaltCloudSystemExit(
"Specified datastore: '{}' does not exist".format(datastore) f"Specified datastore: '{datastore}' does not exist"
) )
if host: if host:
@ -3123,7 +3151,7 @@ def create(vm_):
# If the hardware version is specified and if it is different from the current # If the hardware version is specified and if it is different from the current
# hardware version, then schedule a hardware version upgrade # hardware version, then schedule a hardware version upgrade
if hardware_version and object_ref is not None: if hardware_version and object_ref is not None:
hardware_version = "vmx-{:02}".format(hardware_version) hardware_version = f"vmx-{hardware_version:02}"
if hardware_version != object_ref.config.version: if hardware_version != object_ref.config.version:
log.debug( log.debug(
"Scheduling hardware version upgrade from %s to %s", "Scheduling hardware version upgrade from %s to %s",
@ -3153,7 +3181,7 @@ def create(vm_):
elif memory_unit.lower() == "gb": elif memory_unit.lower() == "gb":
memory_mb = int(float(memory_num) * 1024.0) memory_mb = int(float(memory_num) * 1024.0)
else: else:
err_msg = "Invalid memory type specified: '{}'".format(memory_unit) err_msg = f"Invalid memory type specified: '{memory_unit}'"
log.error(err_msg) log.error(err_msg)
return {"Error": err_msg} return {"Error": err_msg}
except (TypeError, ValueError): except (TypeError, ValueError):
@ -3601,7 +3629,7 @@ def rescan_hba(kwargs=None, call=None):
if hba: if hba:
log.info("Rescanning HBA %s on host %s", hba, host_name) log.info("Rescanning HBA %s on host %s", hba, host_name)
host_ref.configManager.storageSystem.RescanHba(hba) host_ref.configManager.storageSystem.RescanHba(hba)
ret = "rescanned HBA {}".format(hba) ret = f"rescanned HBA {hba}"
else: else:
log.info("Rescanning all HBAs on host %s", host_name) log.info("Rescanning all HBAs on host %s", host_name)
host_ref.configManager.storageSystem.RescanAllHba() host_ref.configManager.storageSystem.RescanAllHba()
@ -3879,7 +3907,7 @@ def list_hbas(kwargs=None, call=None):
if hba_type and hba_type not in ["parallel", "block", "iscsi", "fibre"]: if hba_type and hba_type not in ["parallel", "block", "iscsi", "fibre"]:
raise SaltCloudSystemExit( raise SaltCloudSystemExit(
"Specified hba type {} currently not supported.".format(hba_type) f"Specified hba type {hba_type} currently not supported."
) )
host_list = salt.utils.vmware.get_mors_with_properties( host_list = salt.utils.vmware.get_mors_with_properties(
@ -4252,10 +4280,10 @@ def revert_to_snapshot(name, kwargs=None, call=None):
task = vm_ref.RevertToCurrentSnapshot(suppressPowerOn=suppress_power_on) task = vm_ref.RevertToCurrentSnapshot(suppressPowerOn=suppress_power_on)
else: else:
log.debug("Reverting VM %s to snapshot %s", name, snapshot_name) log.debug("Reverting VM %s to snapshot %s", name, snapshot_name)
msg = "reverted to snapshot {}".format(snapshot_name) msg = f"reverted to snapshot {snapshot_name}"
snapshot_ref = _get_snapshot_ref_by_name(vm_ref, snapshot_name) snapshot_ref = _get_snapshot_ref_by_name(vm_ref, snapshot_name)
if snapshot_ref is None: if snapshot_ref is None:
return "specified snapshot '{}' does not exist".format(snapshot_name) return f"specified snapshot '{snapshot_name}' does not exist"
task = snapshot_ref.snapshot.Revert(suppressPowerOn=suppress_power_on) task = snapshot_ref.snapshot.Revert(suppressPowerOn=suppress_power_on)
salt.utils.vmware.wait_for_task(task, name, "revert to snapshot", 5, "info") salt.utils.vmware.wait_for_task(task, name, "revert to snapshot", 5, "info")
@ -4393,7 +4421,7 @@ def convert_to_template(name, kwargs=None, call=None):
vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name) vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)
if vm_ref.config.template: if vm_ref.config.template:
raise SaltCloudSystemExit("{} already a template".format(name)) raise SaltCloudSystemExit(f"{name} already a template")
try: try:
vm_ref.MarkAsTemplate() vm_ref.MarkAsTemplate()
@ -4407,7 +4435,7 @@ def convert_to_template(name, kwargs=None, call=None):
) )
return "failed to convert to teamplate" return "failed to convert to teamplate"
return "{} converted to template".format(name) return f"{name} converted to template"
def add_host(kwargs=None, call=None): def add_host(kwargs=None, call=None):
@ -4529,7 +4557,7 @@ def add_host(kwargs=None, call=None):
("echo", "-n"), stdout=subprocess.PIPE, stderr=subprocess.PIPE ("echo", "-n"), stdout=subprocess.PIPE, stderr=subprocess.PIPE
) )
p2 = subprocess.Popen( p2 = subprocess.Popen(
("openssl", "s_client", "-connect", "{}:443".format(host_name)), ("openssl", "s_client", "-connect", f"{host_name}:443"),
stdin=p1.stdout, stdin=p1.stdout,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
@ -4559,12 +4587,12 @@ def add_host(kwargs=None, call=None):
try: try:
if cluster_name: if cluster_name:
task = cluster_ref.AddHost(spec=spec, asConnected=True) task = cluster_ref.AddHost(spec=spec, asConnected=True)
ret = "added host system to cluster {}".format(cluster_name) ret = f"added host system to cluster {cluster_name}"
if datacenter_name: if datacenter_name:
task = datacenter_ref.hostFolder.AddStandaloneHost( task = datacenter_ref.hostFolder.AddStandaloneHost(
spec=spec, addConnected=True spec=spec, addConnected=True
) )
ret = "added host system to datacenter {}".format(datacenter_name) ret = f"added host system to datacenter {datacenter_name}"
salt.utils.vmware.wait_for_task(task, host_name, "add host system", 5, "info") salt.utils.vmware.wait_for_task(task, host_name, "add host system", 5, "info")
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
if isinstance(exc, vim.fault.SSLVerifyFault): if isinstance(exc, vim.fault.SSLVerifyFault):

View file

@ -124,7 +124,7 @@ def _get_session():
Get a connection to the XenServer host Get a connection to the XenServer host
""" """
api_version = "1.0" api_version = "1.0"
originator = "salt_cloud_{}_driver".format(__virtualname__) originator = f"salt_cloud_{__virtualname__}_driver"
url = config.get_cloud_config_value( url = config.get_cloud_config_value(
"url", get_configured_provider(), __opts__, search_global=False "url", get_configured_provider(), __opts__, search_global=False
) )
@ -550,7 +550,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"starting create", "starting create",
"salt/cloud/{}/creating".format(name), f"salt/cloud/{name}/creating",
args={"name": name, "profile": vm_["profile"], "provider": vm_["driver"]}, args={"name": name, "profile": vm_["profile"], "provider": vm_["driver"]},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -580,7 +580,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"requesting instance", "requesting instance",
"salt/cloud/{}/requesting".format(name), f"salt/cloud/{name}/requesting",
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
) )
@ -623,7 +623,7 @@ def create(vm_):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"created instance", "created instance",
"salt/cloud/{}/created".format(name), f"salt/cloud/{name}/created",
args={"name": name, "profile": vm_["profile"], "provider": vm_["driver"]}, args={"name": name, "profile": vm_["profile"], "provider": vm_["driver"]},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -923,7 +923,7 @@ def reboot(name, call=None, session=None):
_run_async_task(task, session) _run_async_task(task, session)
return show_instance(name) return show_instance(name)
else: else:
return "{} is not running to be rebooted".format(name) return f"{name} is not running to be rebooted"
def _get_vm(name=None, session=None): def _get_vm(name=None, session=None):
@ -984,7 +984,7 @@ def destroy(name=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -1009,7 +1009,7 @@ def destroy(name=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -1134,7 +1134,7 @@ def vif_list(name, call=None, kwargs=None):
x = 0 x = 0
for vif in vifs: for vif in vifs:
vif_record = session.xenapi.VIF.get_record(vif) vif_record = session.xenapi.VIF.get_record(vif)
data["vif-{}".format(x)] = vif_record data[f"vif-{x}"] = vif_record
x += 1 x += 1
ret[name] = data ret[name] = data
return ret return ret
@ -1168,7 +1168,7 @@ def vbd_list(name=None, call=None):
x = 0 x = 0
for vbd in vbds: for vbd in vbds:
vbd_record = session.xenapi.VBD.get_record(vbd) vbd_record = session.xenapi.VBD.get_record(vbd)
data["vbd-{}".format(x)] = vbd_record data[f"vbd-{x}"] = vbd_record
x += 1 x += 1
ret = data ret = data
return ret return ret
@ -1219,7 +1219,7 @@ def destroy_vm_vdis(name=None, session=None, call=None):
vdi_record = session.xenapi.VDI.get_record(vbd_record["VDI"]) vdi_record = session.xenapi.VDI.get_record(vbd_record["VDI"])
if "iso" not in vdi_record["name_label"]: if "iso" not in vdi_record["name_label"]:
session.xenapi.VDI.destroy(vbd_record["VDI"]) session.xenapi.VDI.destroy(vbd_record["VDI"])
ret["vdi-{}".format(x)] = vdi_record["name_label"] ret[f"vdi-{x}"] = vdi_record["name_label"]
x += 1 x += 1
return ret return ret

View file

@ -61,7 +61,7 @@ def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None):
) )
) )
if why: if why:
errormsg += " for {}".format(why) errormsg += f" for {why}"
errormsg += ". Please upgrade." errormsg += ". Please upgrade."
raise ImportError(errormsg) raise ImportError(errormsg)
@ -186,7 +186,7 @@ def get_location(conn, vm_):
return img return img
raise SaltCloudNotFound( raise SaltCloudNotFound(
"The specified location, '{}', could not be found.".format(vm_location) f"The specified location, '{vm_location}', could not be found."
) )
@ -204,9 +204,7 @@ def get_image(conn, vm_):
if vm_image and vm_image in (img_id, img_name): if vm_image and vm_image in (img_id, img_name):
return img return img
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.")
"The specified image, '{}', could not be found.".format(vm_image)
)
def get_size(conn, vm_): def get_size(conn, vm_):
@ -224,9 +222,7 @@ def get_size(conn, vm_):
str(size.name), str(size.name),
): ):
return size return size
raise SaltCloudNotFound( raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.")
"The specified size, '{}', could not be found.".format(vm_size)
)
def script(vm_): def script(vm_):
@ -257,7 +253,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroying instance", "destroying instance",
"salt/cloud/{}/destroying".format(name), f"salt/cloud/{name}/destroying",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -296,7 +292,7 @@ def destroy(name, conn=None, call=None):
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"destroyed instance", "destroyed instance",
"salt/cloud/{}/destroyed".format(name), f"salt/cloud/{name}/destroyed",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],
@ -338,8 +334,8 @@ def reboot(name, conn=None):
# Fire reboot action # Fire reboot action
__utils__["cloud.fire_event"]( __utils__["cloud.fire_event"](
"event", "event",
"{} has been rebooted".format(name), f"{name} has been rebooted",
"salt/cloud/{}/rebooting".format(name), f"salt/cloud/{name}/rebooting",
args={"name": name}, args={"name": name},
sock_dir=__opts__["sock_dir"], sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"], transport=__opts__["transport"],

View file

@ -1,6 +1,7 @@
""" """
All salt configuration loading and defaults should be in this module All salt configuration loading and defaults should be in this module
""" """
import codecs import codecs
import glob import glob
import logging import logging

View file

@ -8,7 +8,6 @@
Common salt configuration schemas Common salt configuration schemas
""" """
from salt.utils.schema import ArrayItem, OneOfItem, Schema, StringItem from salt.utils.schema import ArrayItem, OneOfItem, Schema, StringItem
@ -26,7 +25,7 @@ class DefaultIncludeConfig(StringItem):
description = __doc__ description = __doc__
def __init__(self, default=None, pattern=None, **kwargs): def __init__(self, default=None, pattern=None, **kwargs):
default = "{}/*.conf".format(self.__confd_directory__) default = f"{self.__confd_directory__}/*.conf"
pattern = r"(?:.*)/\*\.conf" pattern = r"(?:.*)/\*\.conf"
super().__init__(default=default, pattern=pattern, **kwargs) super().__init__(default=default, pattern=pattern, **kwargs)

View file

@ -8,7 +8,6 @@
ESX Cluster configuration schemas ESX Cluster configuration schemas
""" """
from salt.utils.schema import ( from salt.utils.schema import (
AnyOfItem, AnyOfItem,
ArrayItem, ArrayItem,

View file

@ -8,7 +8,6 @@
ESX Datacenter configuration schemas ESX Datacenter configuration schemas
""" """
from salt.utils.schema import ArrayItem, IntegerItem, Schema, StringItem from salt.utils.schema import ArrayItem, IntegerItem, Schema, StringItem

Some files were not shown because too many files have changed in this diff Show more