diff --git a/salt/modules/lxc.py b/salt/modules/lxc.py index 7db7855067c5..9d04963ba789 100644 --- a/salt/modules/lxc.py +++ b/salt/modules/lxc.py @@ -119,7 +119,7 @@ def version(): ver = Version(cversion["stdout"]) if ver < Version("1.0"): raise CommandExecutionError("LXC should be at least 1.0") - __context__[k] = "{}".format(ver) + __context__[k] = f"{ver}" return __context__.get(k, None) @@ -141,7 +141,7 @@ def _ip_sort(ip): idx = "201" elif "::" in ip: idx = "100" - return "{}___{}".format(idx, ip) + return f"{idx}___{ip}" def search_lxc_bridges(): @@ -173,7 +173,7 @@ def search_lxc_bridges(): for ifc, ip in __grains__.get("ip_interfaces", {}).items(): if ifc in running_bridges: bridges.add(ifc) - elif os.path.exists("/sys/devices/virtual/net/{}/bridge".format(ifc)): + elif os.path.exists(f"/sys/devices/virtual/net/{ifc}/bridge"): bridges.add(ifc) bridges = list(bridges) # if we found interfaces that have lxc in their names @@ -186,7 +186,7 @@ def sort_bridges(a): pref = "a" elif "br0" == a: pref = "c" - return "{}_{}".format(pref, a) + return f"{pref}_{a}" bridges.sort(key=sort_bridges) __context__["lxc.bridges"] = bridges @@ -439,12 +439,12 @@ def _cloud_get(k, default=None): if ip: fullip = ip if netmask: - fullip += "/{}".format(netmask) + fullip += f"/{netmask}" eth0["ipv4"] = fullip if mac is not None: eth0["mac"] = mac for ix, iopts in enumerate(_cloud_get("additional_ips", [])): - ifh = "eth{}".format(ix + 1) + ifh = f"eth{ix + 1}" ethx = nic_opts.setdefault(ifh, {}) if gw is None: gw = iopts.get("gateway", ethx.get("gateway", None)) @@ -465,7 +465,7 @@ def _cloud_get(k, default=None): ethx["ipv4"] = aip nm = iopts.get("netmask", "") if nm: - ethx["ipv4"] += "/{}".format(nm) + ethx["ipv4"] += f"/{nm}" for i in ("mac", "hwaddr"): if i in iopts: ethx["mac"] = iopts[i] @@ -543,7 +543,7 @@ def _get_profile(key, name, **kwargs): profile_match = {} else: profile_match = __salt__["config.get"]( - "lxc.{1}:{0}".format(name, key), default=None, merge="recurse" + f"lxc.{key}:{name}", default=None, merge="recurse" ) if profile_match is None: # No matching profile, make the profile an empty dict so that @@ -551,7 +551,7 @@ def _get_profile(key, name, **kwargs): profile_match = {} if not isinstance(profile_match, dict): - raise CommandExecutionError("lxc.{} must be a dictionary".format(key)) + raise CommandExecutionError(f"lxc.{key} must be a dictionary") # Overlay the kwargs to override matched profile data overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs)) @@ -669,7 +669,7 @@ def _rand_cpu_str(cpu): cpu = int(cpu) avail = __salt__["status.nproc"]() if cpu < avail: - return "0-{}".format(avail) + return f"0-{avail}" to_set = set() while len(to_set) < cpu: choice = random.randint(0, avail - 1) @@ -832,7 +832,7 @@ def _network_conf(conf_tuples=None, **kwargs): "ipv6", ]: continue - ret.append({"lxc.network.{}".format(key): val}) + ret.append({f"lxc.network.{key}": val}) # gateway (in automode) must be appended following network conf ! if not gateway: gateway = args.get("gateway", None) @@ -892,7 +892,7 @@ def _get_lxc_default_data(**kwargs): for k in ["utsname", "rootfs"]: val = kwargs.get(k, None) if val is not None: - ret["lxc.{}".format(k)] = val + ret[f"lxc.{k}"] = val autostart = kwargs.get("autostart") # autostart can have made in kwargs, but with the None # value which is invalid, we need an explicit boolean @@ -1115,7 +1115,7 @@ def select(key, default=None): hash_ = salt.utils.hashutils.get_hash( img_tar, __salt__["config.get"]("hash_type") ) - name = "__base_{}_{}_{}".format(proto, img_name, hash_) + name = f"__base_{proto}_{img_name}_{hash_}" if not exists(name, path=path): create( name, template=template, image=image, path=path, vgname=vgname, **kwargs @@ -1125,11 +1125,11 @@ def select(key, default=None): edit_conf( info(name, path=path)["config"], out_format="commented", - **{"lxc.rootfs": rootfs} + **{"lxc.rootfs": rootfs}, ) return name elif template: - name = "__base_{}".format(template) + name = f"__base_{template}" if not exists(name, path=path): create( name, template=template, image=image, path=path, vgname=vgname, **kwargs @@ -1139,7 +1139,7 @@ def select(key, default=None): edit_conf( info(name, path=path)["config"], out_format="commented", - **{"lxc.rootfs": rootfs} + **{"lxc.rootfs": rootfs}, ) return name return "" @@ -1171,7 +1171,7 @@ def init( bootstrap_args=None, bootstrap_shell=None, bootstrap_url=None, - **kwargs + **kwargs, ): """ Initialize a new container. @@ -1499,7 +1499,7 @@ def select(key, default=None): try: stop(name, path=path) except (SaltInvocationError, CommandExecutionError) as exc: - ret["comment"] = "Unable to stop container: {}".format(exc) + ret["comment"] = f"Unable to stop container: {exc}" if changes: ret["changes"] = changes_dict return ret @@ -1507,7 +1507,7 @@ def select(key, default=None): try: start(name, path=path) except (SaltInvocationError, CommandExecutionError) as exc: - ret["comment"] = "Unable to stop container: {}".format(exc) + ret["comment"] = f"Unable to stop container: {exc}" if changes: ret["changes"] = changes_dict return ret @@ -1515,7 +1515,7 @@ def select(key, default=None): if remove_seed_marker: run( name, - "rm -f '{}'".format(SEED_MARKER), + f"rm -f '{SEED_MARKER}'", path=path, chroot_fallback=False, python_shell=False, @@ -1524,11 +1524,11 @@ def select(key, default=None): # set the default user/password, only the first time if ret.get("result", True) and password: gid = "/.lxc.initial_pass" - gids = [gid, "/lxc.initial_pass", "/.lxc.{}.initial_pass".format(name)] + gids = [gid, "/lxc.initial_pass", f"/.lxc.{name}.initial_pass"] if not any( retcode( name, - 'test -e "{}"'.format(x), + f'test -e "{x}"', chroot_fallback=True, path=path, ignore_retcode=True, @@ -1544,7 +1544,7 @@ def select(key, default=None): default_user not in users and retcode( name, - "id {}".format(default_user), + f"id {default_user}", python_shell=False, path=path, chroot_fallback=True, @@ -1563,7 +1563,7 @@ def select(key, default=None): encrypted=password_encrypted, ) except (SaltInvocationError, CommandExecutionError) as exc: - msg = "{}: Failed to set password".format(user) + exc.strerror + msg = f"{user}: Failed to set password" + exc.strerror # only hardfail in unrecoverable situation: # root cannot be setted up if user == "root": @@ -1591,11 +1591,11 @@ def select(key, default=None): if ret.get("result", True) and dnsservers: # retro compatibility, test also old markers gid = "/.lxc.initial_dns" - gids = [gid, "/lxc.initial_dns", "/lxc.{}.initial_dns".format(name)] + gids = [gid, "/lxc.initial_dns", f"/lxc.{name}.initial_dns"] if not any( retcode( name, - 'test -e "{}"'.format(x), + f'test -e "{x}"', chroot_fallback=True, path=path, ignore_retcode=True, @@ -1628,13 +1628,13 @@ def select(key, default=None): # retro compatibility, test also old markers if remove_seed_marker: - run(name, "rm -f '{}'".format(SEED_MARKER), path=path, python_shell=False) + run(name, f"rm -f '{SEED_MARKER}'", path=path, python_shell=False) gid = "/.lxc.initial_seed" gids = [gid, "/lxc.initial_seed"] if any( retcode( name, - "test -e {}".format(x), + f"test -e {x}", path=path, chroot_fallback=True, ignore_retcode=True, @@ -1703,7 +1703,7 @@ def select(key, default=None): try: stop(name, path=path) except (SaltInvocationError, CommandExecutionError) as exc: - ret["comment"] = "Unable to stop container: {}".format(exc) + ret["comment"] = f"Unable to stop container: {exc}" ret["result"] = False state_post = state(name, path=path) @@ -1711,7 +1711,7 @@ def select(key, default=None): changes.append({"state": {"old": state_pre, "new": state_post}}) if ret.get("result", True): - ret["comment"] = "Container '{}' successfully initialized".format(name) + ret["comment"] = f"Container '{name}' successfully initialized" ret["result"] = True if changes: ret["changes"] = changes_dict @@ -1834,8 +1834,8 @@ def _after_ignition_network_profile(cmd, ret, name, network_profile, path, nic_o # destroy the container if it was partially created cmd = "lxc-destroy" if path: - cmd += " -P {}".format(pipes.quote(path)) - cmd += " -n {}".format(name) + cmd += f" -P {pipes.quote(path)}" + cmd += f" -n {name}" __salt__["cmd.retcode"](cmd, python_shell=False) raise CommandExecutionError( "Container could not be created with cmd '{}': {}".format( @@ -1943,7 +1943,7 @@ def create( # Required params for 'download' template download_template_deps = ("dist", "release", "arch") - cmd = "lxc-create -n {}".format(name) + cmd = f"lxc-create -n {name}" profile = get_container_profile(copy.deepcopy(profile)) kw_overrides = copy.deepcopy(kwargs) @@ -1959,7 +1959,7 @@ def select(key, default=None): path = select("path") if exists(name, path=path): - raise CommandExecutionError("Container '{}' already exists".format(name)) + raise CommandExecutionError(f"Container '{name}' already exists") tvg = select("vgname") vgname = tvg if tvg else __salt__["config.get"]("lxc.vgname") @@ -1997,31 +1997,31 @@ def select(key, default=None): ) options["imgtar"] = img_tar if path: - cmd += " -P {}".format(pipes.quote(path)) + cmd += f" -P {pipes.quote(path)}" if not os.path.exists(path): os.makedirs(path) if config: - cmd += " -f {}".format(config) + cmd += f" -f {config}" if template: - cmd += " -t {}".format(template) + cmd += f" -t {template}" if backing: backing = backing.lower() - cmd += " -B {}".format(backing) + cmd += f" -B {backing}" if backing in ("zfs",): if zfsroot: - cmd += " --zfsroot {}".format(zfsroot) + cmd += f" --zfsroot {zfsroot}" if backing in ("lvm",): if lvname: - cmd += " --lvname {}".format(lvname) + cmd += f" --lvname {lvname}" if vgname: - cmd += " --vgname {}".format(vgname) + cmd += f" --vgname {vgname}" if thinpool: - cmd += " --thinpool {}".format(thinpool) + cmd += f" --thinpool {thinpool}" if backing not in ("dir", "overlayfs"): if fstype: - cmd += " --fstype {}".format(fstype) + cmd += f" --fstype {fstype}" if size: - cmd += " --fssize {}".format(size) + cmd += f" --fssize {size}" if options: if template == "download": @@ -2034,7 +2034,7 @@ def select(key, default=None): ) cmd += " --" for key, val in options.items(): - cmd += " --{} {}".format(key, val) + cmd += f" --{key} {val}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) # please do not merge extra conflicting stuff @@ -2108,13 +2108,11 @@ def select(key, default=None): path = select("path") if exists(name, path=path): - raise CommandExecutionError("Container '{}' already exists".format(name)) + raise CommandExecutionError(f"Container '{name}' already exists") _ensure_exists(orig, path=path) if state(orig, path=path) != "stopped": - raise CommandExecutionError( - "Container '{}' must be stopped to be cloned".format(orig) - ) + raise CommandExecutionError(f"Container '{orig}' must be stopped to be cloned") backing = select("backing") snapshot = select("snapshot") @@ -2132,21 +2130,21 @@ def select(key, default=None): if Version(version()) >= Version("2.0"): # https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html cmd = "lxc-copy" - cmd += " {} -n {} -N {}".format(snapshot, orig, name) + cmd += f" {snapshot} -n {orig} -N {name}" else: # https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html cmd = "lxc-clone" - cmd += " {} -o {} -n {}".format(snapshot, orig, name) + cmd += f" {snapshot} -o {orig} -n {name}" if path: - cmd += " -P {}".format(pipes.quote(path)) + cmd += f" -P {pipes.quote(path)}" if not os.path.exists(path): os.makedirs(path) if backing: backing = backing.lower() - cmd += " -B {}".format(backing) + cmd += f" -B {backing}" if backing not in ("dir", "overlayfs"): if size: - cmd += " -L {}".format(size) + cmd += f" -L {size}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) # please do not merge extra conflicting stuff # inside those two line (ret =, return) @@ -2177,7 +2175,7 @@ def ls_(active=None, cache=True, path=None): salt '*' lxc.ls salt '*' lxc.ls active=True """ - contextvar = "lxc.ls{}".format(path) + contextvar = f"lxc.ls{path}" if active: contextvar += ".active" if cache and (contextvar in __context__): @@ -2186,7 +2184,7 @@ def ls_(active=None, cache=True, path=None): ret = [] cmd = "lxc-ls" if path: - cmd += " -P {}".format(pipes.quote(path)) + cmd += f" -P {pipes.quote(path)}" if active: cmd += " --active" output = __salt__["cmd.run_stdout"](cmd, python_shell=False) @@ -2242,8 +2240,8 @@ def list_(extra=False, limit=None, path=None): for container in ctnrs: cmd = "lxc-info" if path: - cmd += " -P {}".format(pipes.quote(path)) - cmd += " -n {}".format(container) + cmd += f" -P {pipes.quote(path)}" + cmd += f" -n {container}" c_info = __salt__["cmd.run"](cmd, python_shell=False, output_loglevel="debug") c_state = None for line in c_info.splitlines(): @@ -2294,20 +2292,20 @@ def _change_state( return { "result": True, "state": {"old": expected, "new": expected}, - "comment": "Container '{}' already {}".format(name, expected), + "comment": f"Container '{name}' already {expected}", } if cmd == "lxc-destroy": # Kill the container first scmd = "lxc-stop" if path: - scmd += " -P {}".format(pipes.quote(path)) - scmd += " -k -n {}".format(name) + scmd += f" -P {pipes.quote(path)}" + scmd += f" -k -n {name}" __salt__["cmd.run"](scmd, python_shell=False) if path and " -P " not in cmd: - cmd += " -P {}".format(pipes.quote(path)) - cmd += " -n {}".format(name) + cmd += f" -P {pipes.quote(path)}" + cmd += f" -n {name}" # certain lxc commands need to be taken with care (lxc-start) # as te command itself mess with double forks; we must not @@ -2337,8 +2335,8 @@ def _change_state( # some commands do not wait, so we will rcmd = "lxc-wait" if path: - rcmd += " -P {}".format(pipes.quote(path)) - rcmd += " -n {} -s {}".format(name, expected.upper()) + rcmd += f" -P {pipes.quote(path)}" + rcmd += f" -n {name} -s {expected.upper()}" __salt__["cmd.run"](rcmd, python_shell=False, timeout=30) _clear_context() post = state(name, path=path) @@ -2351,7 +2349,7 @@ def _ensure_exists(name, path=None): Raise an exception if the container does not exist """ if not exists(name, path=path): - raise CommandExecutionError("Container '{}' does not exist".format(name)) + raise CommandExecutionError(f"Container '{name}' does not exist") def _ensure_running(name, no_start=False, path=None): @@ -2373,11 +2371,11 @@ def _ensure_running(name, no_start=False, path=None): return start(name, path=path) elif pre == "stopped": if no_start: - raise CommandExecutionError("Container '{}' is not running".format(name)) + raise CommandExecutionError(f"Container '{name}' is not running") return start(name, path=path) elif pre == "frozen": if no_start: - raise CommandExecutionError("Container '{}' is not running".format(name)) + raise CommandExecutionError(f"Container '{name}' is not running") return unfreeze(name, path=path) @@ -2459,13 +2457,11 @@ def start(name, **kwargs): lxc_config = os.path.join(cpath, name, "config") # we try to start, even without config, if global opts are there if os.path.exists(lxc_config): - cmd += " -f {}".format(pipes.quote(lxc_config)) + cmd += f" -f {pipes.quote(lxc_config)}" cmd += " -d" _ensure_exists(name, path=path) if state(name, path=path) == "frozen": - raise CommandExecutionError( - "Container '{}' is frozen, use lxc.unfreeze".format(name) - ) + raise CommandExecutionError(f"Container '{name}' is frozen, use lxc.unfreeze") # lxc-start daemonize itself violently, we must not communicate with it use_vt = kwargs.get("use_vt", None) with_communicate = kwargs.get("with_communicate", False) @@ -2560,11 +2556,11 @@ def freeze(name, **kwargs): start_ = kwargs.get("start", False) if orig_state == "stopped": if not start_: - raise CommandExecutionError("Container '{}' is stopped".format(name)) + raise CommandExecutionError(f"Container '{name}' is stopped") start(name, path=path) cmd = "lxc-freeze" if path: - cmd += " -P {}".format(pipes.quote(path)) + cmd += f" -P {pipes.quote(path)}" ret = _change_state(cmd, name, "frozen", use_vt=use_vt, path=path) if orig_state == "stopped" and start_: ret["state"]["old"] = orig_state @@ -2596,10 +2592,10 @@ def unfreeze(name, path=None, use_vt=None): """ _ensure_exists(name, path=path) if state(name, path=path) == "stopped": - raise CommandExecutionError("Container '{}' is stopped".format(name)) + raise CommandExecutionError(f"Container '{name}' is stopped") cmd = "lxc-unfreeze" if path: - cmd += " -P {}".format(pipes.quote(path)) + cmd += f" -P {pipes.quote(path)}" return _change_state(cmd, name, "running", path=path, use_vt=use_vt) @@ -2635,7 +2631,7 @@ def destroy(name, stop=False, path=None): """ _ensure_exists(name, path=path) if not stop and state(name, path=path) != "stopped": - raise CommandExecutionError("Container '{}' is not stopped".format(name)) + raise CommandExecutionError(f"Container '{name}' is not stopped") return _change_state("lxc-destroy", name, None, path=path) @@ -2684,7 +2680,7 @@ def state(name, path=None): """ # Don't use _ensure_exists() here, it will mess with _change_state() - cachekey = "lxc.state.{}{}".format(name, path) + cachekey = f"lxc.state.{name}{path}" try: return __context__[cachekey] except KeyError: @@ -2693,13 +2689,13 @@ def state(name, path=None): else: cmd = "lxc-info" if path: - cmd += " -P {}".format(pipes.quote(path)) - cmd += " -n {}".format(name) + cmd += f" -P {pipes.quote(path)}" + cmd += f" -n {name}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: _clear_context() raise CommandExecutionError( - "Unable to get state of container '{}'".format(name) + f"Unable to get state of container '{name}'" ) c_infos = ret["stdout"].splitlines() c_state = None @@ -2731,13 +2727,11 @@ def get_parameter(name, parameter, path=None): _ensure_exists(name, path=path) cmd = "lxc-cgroup" if path: - cmd += " -P {}".format(pipes.quote(path)) - cmd += " -n {} {}".format(name, parameter) + cmd += f" -P {pipes.quote(path)}" + cmd += f" -n {name} {parameter}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: - raise CommandExecutionError( - "Unable to retrieve value for '{}'".format(parameter) - ) + raise CommandExecutionError(f"Unable to retrieve value for '{parameter}'") return ret["stdout"].strip() @@ -2762,8 +2756,8 @@ def set_parameter(name, parameter, value, path=None): cmd = "lxc-cgroup" if path: - cmd += " -P {}".format(pipes.quote(path)) - cmd += " -n {} {} {}".format(name, parameter, value) + cmd += f" -P {pipes.quote(path)}" + cmd += f" -n {name} {parameter} {value}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: return False @@ -2787,7 +2781,7 @@ def info(name, path=None): salt '*' lxc.info name """ - cachekey = "lxc.info.{}{}".format(name, path) + cachekey = f"lxc.info.{name}{path}" try: return __context__[cachekey] except KeyError: @@ -2799,9 +2793,7 @@ def info(name, path=None): conf_file = os.path.join(cpath, str(name), "config") if not os.path.isfile(conf_file): - raise CommandExecutionError( - "LXC config file {} does not exist".format(conf_file) - ) + raise CommandExecutionError(f"LXC config file {conf_file} does not exist") ret = {} config = [] @@ -3000,9 +2992,7 @@ def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None): cpath = get_root_path(path) lxc_conf_p = os.path.join(cpath, name, "config") if not os.path.exists(lxc_conf_p): - raise SaltInvocationError( - "Configuration file {} does not exist".format(lxc_conf_p) - ) + raise SaltInvocationError(f"Configuration file {lxc_conf_p} does not exist") changes = {"edited": [], "added": [], "removed": []} ret = {"changes": changes, "result": True, "comment": ""} @@ -3054,17 +3044,15 @@ def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None): conf = "" for key, val in dest_lxc_conf: if not val: - conf += "{}\n".format(key) + conf += f"{key}\n" else: - conf += "{} = {}\n".format(key.strip(), val.strip()) + conf += f"{key.strip()} = {val.strip()}\n" conf_changed = conf != orig_config chrono = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if conf_changed: # DO NOT USE salt.utils.files.fopen here, i got (kiorky) # problems with lxc configs which were wiped ! - with salt.utils.files.fopen( - "{}.{}".format(lxc_conf_p, chrono), "w" - ) as wfic: + with salt.utils.files.fopen(f"{lxc_conf_p}.{chrono}", "w") as wfic: wfic.write(salt.utils.stringutils.to_str(conf)) with salt.utils.files.fopen(lxc_conf_p, "w") as wfic: wfic.write(salt.utils.stringutils.to_str(conf)) @@ -3113,8 +3101,8 @@ def set_dns(name, dnsservers=None, searchdomains=None, path=None): searchdomains = searchdomains.split(",") except AttributeError: raise SaltInvocationError("Invalid input for 'searchdomains' parameter") - dns = ["nameserver {}".format(x) for x in dnsservers] - dns.extend(["search {}".format(x) for x in searchdomains]) + dns = [f"nameserver {x}" for x in dnsservers] + dns.extend([f"search {x}" for x in searchdomains]) dns = "\n".join(dns) + "\n" # we may be using resolvconf in the container # We need to handle that case with care: @@ -3129,7 +3117,7 @@ def set_dns(name, dnsservers=None, searchdomains=None, path=None): # - We finally also set /etc/resolv.conf in all cases rstr = __salt__["test.random_hash"]() # no tmp here, apparmor won't let us execute ! - script = "/sbin/{}_dns.sh".format(rstr) + script = f"/sbin/{rstr}_dns.sh" DNS_SCRIPT = "\n".join( [ # 'set -x', @@ -3153,7 +3141,7 @@ def set_dns(name, dnsservers=None, searchdomains=None, path=None): ] ) result = run_all( - name, "tee {}".format(script), path=path, stdin=DNS_SCRIPT, python_shell=True + name, f"tee {script}", path=path, stdin=DNS_SCRIPT, python_shell=True ) if result["retcode"] == 0: result = run_all( @@ -3170,7 +3158,7 @@ def set_dns(name, dnsservers=None, searchdomains=None, path=None): python_shell=True, ) if result["retcode"] != 0: - error = "Unable to write to /etc/resolv.conf in container '{}'".format(name) + error = f"Unable to write to /etc/resolv.conf in container '{name}'" if result["stderr"]: error += ": {}".format(result["stderr"]) raise CommandExecutionError(error) @@ -3193,12 +3181,12 @@ def running_systemd(name, cache=True, path=None): salt '*' lxc.running_systemd ubuntu """ - k = "lxc.systemd.test.{}{}".format(name, path) + k = f"lxc.systemd.test.{name}{path}" ret = __context__.get(k, None) if ret is None or not cache: rstr = __salt__["test.random_hash"]() # no tmp here, apparmor won't let us execute ! - script = "/sbin/{}_testsystemd.sh".format(rstr) + script = f"/sbin/{rstr}_testsystemd.sh" # ubuntu already had since trusty some bits of systemd but was # still using upstart ... # we need to be a bit more careful that just testing that systemd @@ -3227,7 +3215,7 @@ def running_systemd(name, cache=True, path=None): """ ) result = run_all( - name, "tee {}".format(script), path=path, stdin=_script, python_shell=True + name, f"tee {script}", path=path, stdin=_script, python_shell=True ) if result["retcode"] == 0: result = run_all( @@ -3237,9 +3225,7 @@ def running_systemd(name, cache=True, path=None): python_shell=True, ) else: - raise CommandExecutionError( - "lxc {} failed to copy initd tester".format(name) - ) + raise CommandExecutionError(f"lxc {name} failed to copy initd tester") run_all( name, 'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script), @@ -3361,9 +3347,9 @@ def wait_started(name, path=None, timeout=300): """ if not exists(name, path=path): - raise CommandExecutionError("Container {} does does exists".format(name)) + raise CommandExecutionError(f"Container {name} does does exists") if not state(name, path=path) == "running": - raise CommandExecutionError("Container {} is not running".format(name)) + raise CommandExecutionError(f"Container {name} is not running") ret = False if running_systemd(name, path=path): test_started = test_sd_started_state @@ -3520,7 +3506,7 @@ def bootstrap( seeded = ( retcode( name, - "test -e '{}'".format(SEED_MARKER), + f"test -e '{SEED_MARKER}'", path=path, chroot_fallback=True, ignore_retcode=True, @@ -3543,9 +3529,9 @@ def bootstrap( if needs_install or force_install or unconditional_install: if install: rstr = __salt__["test.random_hash"]() - configdir = "/var/tmp/.c_{}".format(rstr) + configdir = f"/var/tmp/.c_{rstr}" - cmd = "install -m 0700 -d {}".format(configdir) + cmd = f"install -m 0700 -d {configdir}" if run_all(name, cmd, path=path, python_shell=False)["retcode"] != 0: log.error("tmpdir %s creation failed %s", configdir, cmd) return False @@ -3553,11 +3539,11 @@ def bootstrap( bs_ = __salt__["config.gather_bootstrap_script"]( bootstrap=bootstrap_url ) - script = "/sbin/{}_bootstrap.sh".format(rstr) + script = f"/sbin/{rstr}_bootstrap.sh" copy_to(name, bs_, script, path=path) result = run_all( name, - 'sh -c "chmod +x {}"'.format(script), + f'sh -c "chmod +x {script}"', path=path, python_shell=True, ) @@ -3631,7 +3617,7 @@ def bootstrap( freeze(name, path=path) # mark seeded upon successful install if ret: - run(name, "touch '{}'".format(SEED_MARKER), path=path, python_shell=False) + run(name, f"touch '{SEED_MARKER}'", path=path, python_shell=False) return ret @@ -3652,7 +3638,7 @@ def attachable(name, path=None): salt 'minion' lxc.attachable ubuntu """ - cachekey = "lxc.attachable{}{}".format(name, path) + cachekey = f"lxc.attachable{name}{path}" try: return __context__[cachekey] except KeyError: @@ -3662,8 +3648,8 @@ def attachable(name, path=None): log.debug("Checking if LXC container %s is attachable", name) cmd = "lxc-attach" if path: - cmd += " -P {}".format(pipes.quote(path)) - cmd += " --clear-env -n {} -- /usr/bin/env".format(name) + cmd += f" -P {pipes.quote(path)}" + cmd += f" --clear-env -n {name} -- /usr/bin/env" result = ( __salt__["cmd.retcode"]( cmd, python_shell=False, output_loglevel="quiet", ignore_retcode=True @@ -3719,7 +3705,7 @@ def _run( ) else: if not chroot_fallback: - raise CommandExecutionError("{} is not attachable.".format(name)) + raise CommandExecutionError(f"{name} is not attachable.") rootfs = info(name, path=path).get("rootfs") # Set context var to make cmd.run_chroot run cmd.run instead of # cmd.run_all. @@ -4214,7 +4200,7 @@ def _get_md5(name, path): Get the MD5 checksum of a file from a container """ output = run_stdout( - name, 'md5sum "{}"'.format(path), chroot_fallback=True, ignore_retcode=True + name, f'md5sum "{path}"', chroot_fallback=True, ignore_retcode=True ) try: return output.split()[0] @@ -4381,7 +4367,7 @@ def write_conf(conf_file, conf): line[key], (str, (str,), (int,), float), ): - out_line = " = ".join((key, "{}".format(line[key]))) + out_line = " = ".join((key, f"{line[key]}")) elif isinstance(line[key], dict): out_line = " = ".join((key, line[key]["value"])) if "comment" in line[key]: @@ -4474,7 +4460,7 @@ def edit_conf( net_changes = _config_list( conf, only_net=True, - **{"network_profile": DEFAULT_NIC, "nic_opts": nic_opts} + **{"network_profile": DEFAULT_NIC, "nic_opts": nic_opts}, ) if net_changes: lxc_config.extend(net_changes) @@ -4524,20 +4510,20 @@ def reboot(name, path=None): salt 'minion' lxc.reboot myvm """ - ret = {"result": True, "changes": {}, "comment": "{} rebooted".format(name)} + ret = {"result": True, "changes": {}, "comment": f"{name} rebooted"} does_exist = exists(name, path=path) if does_exist and (state(name, path=path) == "running"): try: stop(name, path=path) except (SaltInvocationError, CommandExecutionError) as exc: - ret["comment"] = "Unable to stop container: {}".format(exc) + ret["comment"] = f"Unable to stop container: {exc}" ret["result"] = False return ret if does_exist and (state(name, path=path) != "running"): try: start(name, path=path) except (SaltInvocationError, CommandExecutionError) as exc: - ret["comment"] = "Unable to stop container: {}".format(exc) + ret["comment"] = f"Unable to stop container: {exc}" ret["result"] = False return ret ret["changes"][name] = "rebooted" @@ -4559,7 +4545,7 @@ def reconfigure( utsname=None, rootfs=None, path=None, - **kwargs + **kwargs, ): """ Reconfigure a container. @@ -4625,7 +4611,7 @@ def reconfigure( path = os.path.join(cpath, name, "config") ret = { "name": name, - "comment": "config for {} up to date".format(name), + "comment": f"config for {name} up to date", "result": True, "changes": changes, } @@ -4677,7 +4663,7 @@ def select(key, default=None): edit_conf(path, out_format="commented", lxc_config=new_cfg) chunks = read_conf(path, out_format="commented") if old_chunks != chunks: - ret["comment"] = "{} lxc config updated".format(name) + ret["comment"] = f"{name} lxc config updated" if state(name, path=path) == "running": cret = reboot(name, path=path) ret["result"] = cret["result"] @@ -4763,9 +4749,9 @@ def get_pid(name, path=None): """ if name not in list_(limit="running", path=path): raise CommandExecutionError( - "Container {} is not running, can't determine PID".format(name) + f"Container {name} is not running, can't determine PID" ) - info = __salt__["cmd.run"]("lxc-info -n {}".format(name)).split("\n") + info = __salt__["cmd.run"](f"lxc-info -n {name}").split("\n") pid = [ line.split(":")[1].strip() for line in info @@ -4812,21 +4798,19 @@ def add_veth(name, interface_name, bridge=None, path=None): raise CommandExecutionError( "Directory /var/run required for lxc.add_veth doesn't exists" ) - if not __salt__["file.file_exists"]("/proc/{}/ns/net".format(pid)): + if not __salt__["file.file_exists"](f"/proc/{pid}/ns/net"): raise CommandExecutionError( - "Proc file for container {} network namespace doesn't exists".format(name) + f"Proc file for container {name} network namespace doesn't exists" ) if not __salt__["file.directory_exists"]("/var/run/netns"): __salt__["file.mkdir"]("/var/run/netns") # Ensure that the symlink is up to date (change on container restart) - if __salt__["file.is_link"]("/var/run/netns/{}".format(name)): - __salt__["file.remove"]("/var/run/netns/{}".format(name)) + if __salt__["file.is_link"](f"/var/run/netns/{name}"): + __salt__["file.remove"](f"/var/run/netns/{name}") - __salt__["file.symlink"]( - "/proc/{}/ns/net".format(pid), "/var/run/netns/{}".format(name) - ) + __salt__["file.symlink"](f"/proc/{pid}/ns/net", f"/var/run/netns/{name}") # Ensure that interface doesn't exists interface_exists = 0 == __salt__["cmd.retcode"]( @@ -4851,12 +4835,10 @@ def add_veth(name, interface_name, bridge=None, path=None): ) != 0 ): + raise CommandExecutionError(f"Error while creating the veth pair {random_veth}") + if __salt__["cmd.retcode"](f"ip link set dev {random_veth} up") != 0: raise CommandExecutionError( - "Error while creating the veth pair {}".format(random_veth) - ) - if __salt__["cmd.retcode"]("ip link set dev {} up".format(random_veth)) != 0: - raise CommandExecutionError( - "Error while bringing up host-side veth {}".format(random_veth) + f"Error while bringing up host-side veth {random_veth}" ) # Attach it to the container @@ -4872,7 +4854,7 @@ def add_veth(name, interface_name, bridge=None, path=None): ) ) - __salt__["file.remove"]("/var/run/netns/{}".format(name)) + __salt__["file.remove"](f"/var/run/netns/{name}") if bridge is not None: __salt__["bridge.addif"](bridge, random_veth) diff --git a/salt/modules/network.py b/salt/modules/network.py index 473ce7a7cfe9..de4079567673 100644 --- a/salt/modules/network.py +++ b/salt/modules/network.py @@ -299,7 +299,7 @@ def _netstat_bsd(): ret = [] if __grains__["kernel"] == "NetBSD": for addr_family in ("inet", "inet6"): - cmd = "netstat -f {} -an | tail -n+3".format(addr_family) + cmd = f"netstat -f {addr_family} -an | tail -n+3" out = __salt__["cmd.run"](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() @@ -382,7 +382,7 @@ def _netstat_sunos(): ret = [] for addr_family in ("inet", "inet6"): # Lookup TCP connections - cmd = "netstat -f {} -P tcp -an | tail +5".format(addr_family) + cmd = f"netstat -f {addr_family} -P tcp -an | tail +5" out = __salt__["cmd.run"](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() @@ -397,7 +397,7 @@ def _netstat_sunos(): } ) # Lookup UDP connections - cmd = "netstat -f {} -P udp -an | tail +5".format(addr_family) + cmd = f"netstat -f {addr_family} -P udp -an | tail +5" out = __salt__["cmd.run"](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() @@ -421,7 +421,7 @@ def _netstat_aix(): ## for addr_family in ('inet', 'inet6'): for addr_family in ("inet",): # Lookup connections - cmd = "netstat -n -a -f {} | tail -n +3".format(addr_family) + cmd = f"netstat -n -a -f {addr_family} | tail -n +3" out = __salt__["cmd.run"](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() @@ -1012,7 +1012,7 @@ def traceroute(host): "ip": traceline[2], } for idx, delay in enumerate(delays): - result["ms{}".format(idx + 1)] = delay + result[f"ms{idx + 1}"] = delay except IndexError: result = {} @@ -1454,7 +1454,7 @@ def mod_hostname(hostname): # Grab the old hostname so we know which hostname to change and then # change the hostname using the hostname command if hostname_cmd.endswith("hostnamectl"): - result = __salt__["cmd.run_all"]("{} status".format(hostname_cmd)) + result = __salt__["cmd.run_all"](f"{hostname_cmd} status") if 0 == result["retcode"]: out = result["stdout"] for line in out.splitlines(): @@ -1486,7 +1486,7 @@ def mod_hostname(hostname): ) return False elif not __utils__["platform.is_sunos"](): - __salt__["cmd.run"]("{} {}".format(hostname_cmd, hostname)) + __salt__["cmd.run"](f"{hostname_cmd} {hostname}") else: __salt__["cmd.run"]("{} -S {}".format(uname_cmd, hostname.split(".")[0])) @@ -1544,7 +1544,7 @@ def mod_hostname(hostname): ) if __salt__["cmd.run_all"](nirtcfg_cmd)["retcode"] != 0: raise CommandExecutionError( - "Couldn't set hostname to: {}\n".format(str_hostname) + f"Couldn't set hostname to: {str_hostname}\n" ) elif __grains__["os_family"] == "OpenBSD": with __utils__["files.fopen"]("/etc/myname", "w") as fh_: @@ -1720,7 +1720,7 @@ def _get_bufsize_linux(iface): """ ret = {"result": False} - cmd = "/sbin/ethtool -g {}".format(iface) + cmd = f"/sbin/ethtool -g {iface}" out = __salt__["cmd.run"](cmd) pat = re.compile(r"^(.+):\s+(\d+)$") suffix = "max-" @@ -1824,7 +1824,7 @@ def routes(family=None): salt '*' network.routes """ if family != "inet" and family != "inet6" and family is not None: - raise CommandExecutionError("Invalid address family {}".format(family)) + raise CommandExecutionError(f"Invalid address family {family}") if __grains__["kernel"] == "Linux": if not __utils__["path.which"]("netstat"): @@ -1868,7 +1868,7 @@ def default_route(family=None): salt '*' network.default_route """ if family != "inet" and family != "inet6" and family is not None: - raise CommandExecutionError("Invalid address family {}".format(family)) + raise CommandExecutionError(f"Invalid address family {family}") _routes = routes(family) @@ -1926,7 +1926,7 @@ def get_route(ip): """ if __grains__["kernel"] == "Linux": - cmd = "ip route get {}".format(ip) + cmd = f"ip route get {ip}" out = __salt__["cmd.run"](cmd, python_shell=True) regexp = re.compile( r"(via\s+(?P[\w\.:]+))?\s+dev\s+(?P[\w\.\:\-]+)\s+.*src\s+(?P[\w\.:]+)" @@ -1950,7 +1950,7 @@ def get_route(ip): # flags: # recvpipe sendpipe ssthresh rtt,ms rttvar,ms hopcount mtu expire # 0 0 0 0 0 0 1500 0 - cmd = "/usr/sbin/route -n get {}".format(ip) + cmd = f"/usr/sbin/route -n get {ip}" out = __salt__["cmd.run"](cmd, python_shell=False) ret = {"destination": ip, "gateway": None, "interface": None, "source": None} @@ -1979,7 +1979,7 @@ def get_route(ip): # flags: # use mtu expire # 8352657 0 0 - cmd = "route -n get {}".format(ip) + cmd = f"route -n get {ip}" out = __salt__["cmd.run"](cmd, python_shell=False) ret = {"destination": ip, "gateway": None, "interface": None, "source": None} @@ -2007,7 +2007,7 @@ def get_route(ip): # flags: # recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire # 0 0 0 0 0 0 0 -68642 - cmd = "route -n get {}".format(ip) + cmd = f"route -n get {ip}" out = __salt__["cmd.run"](cmd, python_shell=False) ret = {"destination": ip, "gateway": None, "interface": None, "source": None} diff --git a/salt/modules/nspawn.py b/salt/modules/nspawn.py index b0aaca413e4c..3c8e8c0f76f9 100644 --- a/salt/modules/nspawn.py +++ b/salt/modules/nspawn.py @@ -81,7 +81,7 @@ def _ensure_exists(wrapped): @functools.wraps(wrapped) def check_exists(name, *args, **kwargs): if not exists(name): - raise CommandExecutionError("Container '{}' does not exist".format(name)) + raise CommandExecutionError(f"Container '{name}' does not exist") return wrapped(name, *args, **salt.utils.args.clean_kwargs(**kwargs)) return check_exists @@ -115,14 +115,14 @@ def _make_container_root(name): path = _root(name) if os.path.exists(path): __context__["retcode"] = salt.defaults.exitcodes.SALT_BUILD_FAIL - raise CommandExecutionError("Container {} already exists".format(name)) + raise CommandExecutionError(f"Container {name} already exists") else: try: os.makedirs(path) return path except OSError as exc: raise CommandExecutionError( - "Unable to make container root directory {}: {}".format(name, exc) + f"Unable to make container root directory {name}: {exc}" ) @@ -132,10 +132,8 @@ def _build_failed(dst, name): shutil.rmtree(dst) except OSError as exc: if exc.errno != errno.ENOENT: - raise CommandExecutionError( - "Unable to cleanup container root dir {}".format(dst) - ) - raise CommandExecutionError("Container {} failed to build".format(name)) + raise CommandExecutionError(f"Unable to cleanup container root dir {dst}") + raise CommandExecutionError(f"Container {name} failed to build") def _bootstrap_arch(name, **kwargs): @@ -147,7 +145,7 @@ def _bootstrap_arch(name, **kwargs): "pacstrap not found, is the arch-install-scripts package installed?" ) dst = _make_container_root(name) - cmd = "pacstrap -c -d {} base".format(dst) + cmd = f"pacstrap -c -d {dst} base" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: _build_failed(dst, name) @@ -183,7 +181,7 @@ def _bootstrap_debian(name, **kwargs): ) dst = _make_container_root(name) - cmd = "debootstrap --arch=amd64 {} {}".format(version, dst) + cmd = f"debootstrap --arch=amd64 {version} {dst}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: _build_failed(dst, name) @@ -224,7 +222,7 @@ def _bootstrap_ubuntu(name, **kwargs): else: version = "xenial" dst = _make_container_root(name) - cmd = "debootstrap --arch=amd64 {} {}".format(version, dst) + cmd = f"debootstrap --arch=amd64 {version} {dst}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: _build_failed(dst, name) @@ -258,7 +256,7 @@ def _ensure_systemd(version): try: version = int(version) except ValueError: - raise CommandExecutionError("Invalid version '{}'".format(version)) + raise CommandExecutionError(f"Invalid version '{version}'") try: installed = _sd_version() @@ -280,7 +278,7 @@ def _machinectl(cmd, output_loglevel="debug", ignore_retcode=False, use_vt=False """ prefix = "machinectl --no-legend --no-pager" return __salt__["cmd.run_all"]( - "{} {}".format(prefix, cmd), + f"{prefix} {cmd}", output_loglevel=output_loglevel, ignore_retcode=ignore_retcode, use_vt=use_vt, @@ -350,9 +348,7 @@ def pid(name): try: return int(info(name).get("PID")) except (TypeError, ValueError) as exc: - raise CommandExecutionError( - "Unable to get PID for container '{}': {}".format(name, exc) - ) + raise CommandExecutionError(f"Unable to get PID for container '{name}': {exc}") def run( @@ -706,9 +702,9 @@ def bootstrap_container(name, dist=None, version=None): dist = __grains__["os"].lower() log.debug("nspawn.bootstrap: no dist provided, defaulting to '%s'", dist) try: - return globals()["_bootstrap_{}".format(dist)](name, version=version) + return globals()[f"_bootstrap_{dist}"](name, version=version) except KeyError: - raise CommandExecutionError('Unsupported distribution "{}"'.format(dist)) + raise CommandExecutionError(f'Unsupported distribution "{dist}"') def _needs_install(name): @@ -786,7 +782,7 @@ def bootstrap_salt( needs_install = _needs_install(name) else: needs_install = True - seeded = retcode(name, "test -e '{}'".format(SEED_MARKER)) == 0 + seeded = retcode(name, f"test -e '{SEED_MARKER}'") == 0 tmp = tempfile.mkdtemp() if seeded and not unconditional_install: ret = True @@ -803,20 +799,20 @@ def bootstrap_salt( if needs_install or force_install or unconditional_install: if install: rstr = __salt__["test.random_hash"]() - configdir = "/tmp/.c_{}".format(rstr) - run(name, "install -m 0700 -d {}".format(configdir), python_shell=False) + configdir = f"/tmp/.c_{rstr}" + run(name, f"install -m 0700 -d {configdir}", python_shell=False) bs_ = __salt__["config.gather_bootstrap_script"]( bootstrap=bootstrap_url ) dest_dir = os.path.join("/tmp", rstr) for cmd in [ - "mkdir -p {}".format(dest_dir), - "chmod 700 {}".format(dest_dir), + f"mkdir -p {dest_dir}", + f"chmod 700 {dest_dir}", ]: if run_stdout(name, cmd): log.error("tmpdir %s creation failed (%s)", dest_dir, cmd) return False - copy_to(name, bs_, "{}/bootstrap.sh".format(dest_dir), makedirs=True) + copy_to(name, bs_, f"{dest_dir}/bootstrap.sh", makedirs=True) copy_to(name, cfg_files["config"], os.path.join(configdir, "minion")) copy_to( name, cfg_files["privkey"], os.path.join(configdir, "minion.pem") @@ -849,7 +845,7 @@ def bootstrap_salt( stop(name) # mark seeded upon successful install if ret: - run(name, "touch '{}'".format(SEED_MARKER), python_shell=False) + run(name, f"touch '{SEED_MARKER}'", python_shell=False) return ret @@ -933,7 +929,7 @@ def exists(name): salt myminion nspawn.exists """ - contextkey = "nspawn.exists.{}".format(name) + contextkey = f"nspawn.exists.{name}" if contextkey in __context__: return __context__[contextkey] __context__[contextkey] = name in list_all() @@ -952,7 +948,7 @@ def state(name): salt myminion nspawn.state """ try: - cmd = "show {} --property=State".format(name) + cmd = f"show {name} --property=State" return _machinectl(cmd, ignore_retcode=True)["stdout"].split("=")[-1] except IndexError: return "stopped" @@ -992,11 +988,9 @@ def info(name, **kwargs): # Have to parse 'machinectl status' here since 'machinectl show' doesn't # contain IP address info or OS info. *shakes fist angrily* - c_info = _machinectl("status {}".format(name)) + c_info = _machinectl(f"status {name}") if c_info["retcode"] != 0: - raise CommandExecutionError( - "Unable to get info for container '{}'".format(name) - ) + raise CommandExecutionError(f"Unable to get info for container '{name}'") # Better human-readable names. False means key should be ignored. key_name_map = { "Iface": "Network Interface", @@ -1052,7 +1046,7 @@ def enable(name): salt myminion nspawn.enable """ - cmd = "systemctl enable systemd-nspawn@{}".format(name) + cmd = f"systemctl enable systemd-nspawn@{name}" if __salt__["cmd.retcode"](cmd, python_shell=False) != 0: __context__["retcode"] = salt.defaults.exitcodes.EX_UNAVAILABLE return False @@ -1070,7 +1064,7 @@ def disable(name): salt myminion nspawn.enable """ - cmd = "systemctl disable systemd-nspawn@{}".format(name) + cmd = f"systemctl disable systemd-nspawn@{name}" if __salt__["cmd.retcode"](cmd, python_shell=False) != 0: __context__["retcode"] = salt.defaults.exitcodes.EX_UNAVAILABLE return False @@ -1089,9 +1083,9 @@ def start(name): salt myminion nspawn.start """ if _sd_version() >= 219: - ret = _machinectl("start {}".format(name)) + ret = _machinectl(f"start {name}") else: - cmd = "systemctl start systemd-nspawn@{}".format(name) + cmd = f"systemctl start systemd-nspawn@{name}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: @@ -1112,9 +1106,9 @@ def stop(name, kill=False): action = "terminate" else: action = "poweroff" - ret = _machinectl("{} {}".format(action, name)) + ret = _machinectl(f"{action} {name}") else: - cmd = "systemctl stop systemd-nspawn@{}".format(name) + cmd = f"systemctl stop systemd-nspawn@{name}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: @@ -1204,7 +1198,7 @@ def reboot(name, kill=False): """ if _sd_version() >= 219: if state(name) == "running": - ret = _machinectl("reboot {}".format(name)) + ret = _machinectl(f"reboot {name}") else: # 'machinectl reboot' will fail on a stopped container return start(name) @@ -1214,7 +1208,7 @@ def reboot(name, kill=False): # we need stop and start the container in separate actions. # First stop the container - cmd = "systemctl stop systemd-nspawn@{}".format(name) + cmd = f"systemctl stop systemd-nspawn@{name}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) # Now check if successful if ret["retcode"] != 0: @@ -1222,7 +1216,7 @@ def reboot(name, kill=False): return False # Finally, start the container back up. No need to check the retcode a # second time, it'll be checked below once we exit the if/else block. - cmd = "systemctl start systemd-nspawn@{}".format(name) + cmd = f"systemctl start systemd-nspawn@{name}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: @@ -1257,15 +1251,13 @@ def remove(name, stop=False): salt '*' nspawn.remove foo stop=True """ if not stop and state(name) != "stopped": - raise CommandExecutionError("Container '{}' is not stopped".format(name)) + raise CommandExecutionError(f"Container '{name}' is not stopped") def _failed_remove(name, exc): - raise CommandExecutionError( - "Unable to remove container '{}': {}".format(name, exc) - ) + raise CommandExecutionError(f"Unable to remove container '{name}': {exc}") if _sd_version() >= 219: - ret = _machinectl("remove {}".format(name)) + ret = _machinectl(f"remove {name}") if ret["retcode"] != 0: __context__["retcode"] = salt.defaults.exitcodes.EX_UNAVAILABLE _failed_remove(name, ret["stderr"]) @@ -1315,10 +1307,10 @@ def copy_to(name, source, dest, overwrite=False, makedirs=False): if source.startswith("salt://"): cached_source = __salt__["cp.cache_file"](source) if not cached_source: - raise CommandExecutionError("Unable to cache {}".format(source)) + raise CommandExecutionError(f"Unable to cache {source}") path = cached_source except AttributeError: - raise SaltInvocationError("Invalid source file {}".format(source)) + raise SaltInvocationError(f"Invalid source file {source}") if _sd_version() >= 219: # TODO: Use machinectl copy-to @@ -1346,13 +1338,13 @@ def _pull_image(pull_type, image, name, **kwargs): """ _ensure_systemd(219) if exists(name): - raise SaltInvocationError("Container '{}' already exists".format(name)) + raise SaltInvocationError(f"Container '{name}' already exists") if pull_type in ("raw", "tar"): valid_kwargs = ("verify",) elif pull_type == "dkr": valid_kwargs = ("index",) else: - raise SaltInvocationError("Unsupported image type '{}'".format(pull_type)) + raise SaltInvocationError(f"Unsupported image type '{pull_type}'") kwargs = salt.utils.args.clean_kwargs(**kwargs) bad_kwargs = { @@ -1384,7 +1376,7 @@ def _bad_verify(): else: if verify not in ("signature", "checksum"): _bad_verify() - pull_opts.append("--verify={}".format(verify)) + pull_opts.append(f"--verify={verify}") elif pull_type == "dkr": # No need to validate the index URL, machinectl will take care of this diff --git a/salt/modules/vagrant.py b/salt/modules/vagrant.py index 0df88afde298..497cddccb7ec 100644 --- a/salt/modules/vagrant.py +++ b/salt/modules/vagrant.py @@ -62,7 +62,7 @@ def _build_sdb_uri(key): Salt node id's are used as the key for vm_ dicts. """ - return "{}{}".format(VAGRANT_SDB_URL, key) + return f"{VAGRANT_SDB_URL}{key}" def _build_machine_uri(machine, cwd): @@ -73,7 +73,7 @@ def _build_machine_uri(machine, cwd): never collide with a Salt node id -- which is important since we will be storing both in the same table. """ - key = "{}?{}".format(machine, os.path.abspath(cwd)) + key = f"{machine}?{os.path.abspath(cwd)}" return _build_sdb_uri(key) @@ -102,9 +102,7 @@ def get_vm_info(name): "Probable sdb driver not found. Check your configuration." ) if vm_ is None or "machine" not in vm_: - raise SaltInvocationError( - "No Vagrant machine defined for Salt_id {}".format(name) - ) + raise SaltInvocationError(f"No Vagrant machine defined for Salt_id {name}") return vm_ @@ -161,7 +159,7 @@ def _vagrant_ssh_config(vm_): """ machine = vm_["machine"] log.info("requesting vagrant ssh-config for VM %s", machine or "(default)") - cmd = "vagrant ssh-config {}".format(machine) + cmd = f"vagrant ssh-config {machine}" reply = __salt__["cmd.shell"]( cmd, runas=vm_.get("runas"), cwd=vm_.get("cwd"), ignore_retcode=True ) @@ -305,12 +303,12 @@ def vm_state(name="", cwd=None): else: if not cwd: raise SaltInvocationError( - "Path to Vagranfile must be defined, but cwd={}".format(cwd) + f"Path to Vagranfile must be defined, but cwd={cwd}" ) machine = "" info = [] - cmd = "vagrant status {}".format(machine) + cmd = f"vagrant status {machine}" reply = __salt__["cmd.shell"](cmd, cwd) log.info("--->\n%s", reply) for line in reply.split("\n"): # build a list of the text reply @@ -404,13 +402,11 @@ def _start( try: machine = vm_["machine"] except KeyError: - raise SaltInvocationError( - "No Vagrant machine defined for Salt_id {}".format(name) - ) + raise SaltInvocationError(f"No Vagrant machine defined for Salt_id {name}") vagrant_provider = vm_.get("vagrant_provider", "") - provider_ = "--provider={}".format(vagrant_provider) if vagrant_provider else "" - cmd = "vagrant up {} {}".format(machine, provider_) + provider_ = f"--provider={vagrant_provider}" if vagrant_provider else "" + cmd = f"vagrant up {machine} {provider_}" ret = __salt__["cmd.run_all"]( cmd, runas=vm_.get("runas"), cwd=vm_.get("cwd"), output_loglevel="info" ) @@ -424,7 +420,7 @@ def _start( break if ret["retcode"] == 0: - return 'Started "{}" using Vagrant machine "{}".'.format(name, machine) + return f'Started "{name}" using Vagrant machine "{machine}".' return False @@ -458,7 +454,7 @@ def stop(name): vm_ = get_vm_info(name) machine = vm_["machine"] - cmd = "vagrant halt {}".format(machine) + cmd = f"vagrant halt {machine}" ret = __salt__["cmd.retcode"](cmd, runas=vm_.get("runas"), cwd=vm_.get("cwd")) return ret == 0 @@ -476,7 +472,7 @@ def pause(name): vm_ = get_vm_info(name) machine = vm_["machine"] - cmd = "vagrant suspend {}".format(machine) + cmd = f"vagrant suspend {machine}" ret = __salt__["cmd.retcode"](cmd, runas=vm_.get("runas"), cwd=vm_.get("cwd")) return ret == 0 @@ -498,7 +494,7 @@ def reboot(name, provision=False): machine = vm_["machine"] prov = "--provision" if provision else "" - cmd = "vagrant reload {} {}".format(machine, prov) + cmd = f"vagrant reload {machine} {prov}" ret = __salt__["cmd.retcode"](cmd, runas=vm_.get("runas"), cwd=vm_.get("cwd")) return ret == 0 @@ -518,14 +514,14 @@ def destroy(name): vm_ = get_vm_info(name) machine = vm_["machine"] - cmd = "vagrant destroy -f {}".format(machine) + cmd = f"vagrant destroy -f {machine}" ret = __salt__["cmd.run_all"]( cmd, runas=vm_.get("runas"), cwd=vm_.get("cwd"), output_loglevel="info" ) if ret["retcode"] == 0: _erase_vm_info(name) - return "Destroyed VM {}".format(name) + return f"Destroyed VM {name}" return False @@ -691,6 +687,6 @@ def get_ssh_config(name, network_mask="", get_private_key=False): ans["private_key"] = salt.utils.stringutils.to_unicode(pks.read()) except OSError as e: raise CommandExecutionError( - "Error processing Vagrant private key file: {}".format(e) + f"Error processing Vagrant private key file: {e}" ) return ans diff --git a/tests/pytests/unit/modules/test_network.py b/tests/pytests/unit/modules/test_network.py index ee7e7e80a85e..671623102aa3 100644 --- a/tests/pytests/unit/modules/test_network.py +++ b/tests/pytests/unit/modules/test_network.py @@ -17,7 +17,7 @@ @pytest.fixture -def configure_loader_modules(): +def configure_loader_modules(minion_opts): ## return {networkmod: {}} utils = salt.loader.utils( minion_opts, whitelist=["network", "path", "platform", "stringutils"]