Upgrade to black 21.7b0

This commit is contained in:
Pedro Algarvio 2021-08-03 07:25:24 +01:00 committed by Gareth J. Greenaway
parent d596b85c7d
commit 9c443d144b
272 changed files with 3756 additions and 2015 deletions

View file

@ -66,7 +66,8 @@ def beacon(config):
# NOTE: lookup current images
current_vms = __salt__["vmadm.list"](
keyed=True, order="uuid,state,alias,hostname,dns_domain",
keyed=True,
order="uuid,state,alias,hostname,dns_domain",
)
# NOTE: apply configuration

View file

@ -364,7 +364,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)

View file

@ -119,7 +119,12 @@ def get_configured_provider():
return config.is_provider_configured(
__opts__,
_get_active_provider_name() or __virtualname__,
("token", "token_pass", "user", "password",),
(
"token",
"token_pass",
"user",
"password",
),
)
@ -331,32 +336,68 @@ def create(vm_):
__opts__, _get_active_provider_name() or __virtualname__, ("token",)
)
group = config.get_cloud_config_value(
"group", vm_, __opts__, search_global=False, default=None,
"group",
vm_,
__opts__,
search_global=False,
default=None,
)
name = vm_["name"]
description = config.get_cloud_config_value(
"description", vm_, __opts__, search_global=False, default=None,
"description",
vm_,
__opts__,
search_global=False,
default=None,
)
ram = config.get_cloud_config_value(
"ram", vm_, __opts__, search_global=False, default=None,
"ram",
vm_,
__opts__,
search_global=False,
default=None,
)
backup_level = config.get_cloud_config_value(
"backup_level", vm_, __opts__, search_global=False, default=None,
"backup_level",
vm_,
__opts__,
search_global=False,
default=None,
)
template = config.get_cloud_config_value(
"template", vm_, __opts__, search_global=False, default=None,
"template",
vm_,
__opts__,
search_global=False,
default=None,
)
password = config.get_cloud_config_value(
"password", vm_, __opts__, search_global=False, default=None,
"password",
vm_,
__opts__,
search_global=False,
default=None,
)
cpu = config.get_cloud_config_value(
"cpu", vm_, __opts__, search_global=False, default=None,
"cpu",
vm_,
__opts__,
search_global=False,
default=None,
)
network = config.get_cloud_config_value(
"network", vm_, __opts__, search_global=False, default=None,
"network",
vm_,
__opts__,
search_global=False,
default=None,
)
location = config.get_cloud_config_value(
"location", vm_, __opts__, search_global=False, default=None,
"location",
vm_,
__opts__,
search_global=False,
default=None,
)
if len(name) > 6:
name = name[0:6]

View file

@ -172,7 +172,7 @@ def get_location(conn, vm_):
# Default to Dallas if not otherwise set
loc = config.get_cloud_config_value("location", vm_, __opts__, default=2)
for location in locations:
if str(loc) in (str(location.id), str(location.name),):
if str(loc) in (str(location.id), str(location.name)):
return location
@ -270,7 +270,7 @@ def get_project(conn, vm_):
return False
for project in projects:
if str(projid) in (str(project.id), str(project.name),):
if str(projid) in (str(project.id), str(project.name)):
return project
log.warning("Couldn't find project %s in projects", projid)

View file

@ -197,7 +197,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)
@ -353,7 +355,11 @@ def create(vm_):
)
private_networking = config.get_cloud_config_value(
"private_networking", vm_, __opts__, search_global=False, default=None,
"private_networking",
vm_,
__opts__,
search_global=False,
default=None,
)
if private_networking is not None:
@ -370,7 +376,11 @@ def create(vm_):
)
backups_enabled = config.get_cloud_config_value(
"backups_enabled", vm_, __opts__, search_global=False, default=None,
"backups_enabled",
vm_,
__opts__,
search_global=False,
default=None,
)
if backups_enabled is not None:
@ -379,7 +389,11 @@ def create(vm_):
kwargs["backups"] = backups_enabled
ipv6 = config.get_cloud_config_value(
"ipv6", vm_, __opts__, search_global=False, default=None,
"ipv6",
vm_,
__opts__,
search_global=False,
default=None,
)
if ipv6 is not None:
@ -388,7 +402,11 @@ def create(vm_):
kwargs["ipv6"] = ipv6
monitoring = config.get_cloud_config_value(
"monitoring", vm_, __opts__, search_global=False, default=None,
"monitoring",
vm_,
__opts__,
search_global=False,
default=None,
)
if monitoring is not None:
@ -413,7 +431,11 @@ def create(vm_):
log.exception("Failed to read userdata from %s: %s", userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
"create_dns_record", vm_, __opts__, search_global=False, default=None,
"create_dns_record",
vm_,
__opts__,
search_global=False,
default=None,
)
if create_dns_record:
@ -701,7 +723,8 @@ def list_keypairs(call=None):
while fetch:
items = query(
method="account/keys", command="?page=" + str(page) + "&per_page=100",
method="account/keys",
command="?page=" + str(page) + "&per_page=100",
)
for key_pair in items["ssh_keys"]:
@ -1031,7 +1054,8 @@ def list_floating_ips(call=None):
while fetch:
items = query(
method="floating_ips", command="?page=" + str(page) + "&per_page=200",
method="floating_ips",
command="?page=" + str(page) + "&per_page=200",
)
for floating_ip in items["floating_ips"]:

View file

@ -2335,7 +2335,11 @@ def query_instance(vm_=None, call=None):
def wait_for_instance(
vm_=None, data=None, ip_address=None, display_ssh_output=True, call=None,
vm_=None,
data=None,
ip_address=None,
display_ssh_output=True,
call=None,
):
"""
Wait for an instance upon creation from the EC2 API, to become available
@ -3707,7 +3711,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full(get_location()), __opts__["query.selection"], call,
list_nodes_full(get_location()),
__opts__["query.selection"],
call,
)
@ -4813,7 +4819,11 @@ def describe_snapshots(kwargs=None, call=None):
def get_console_output(
name=None, location=None, instance_id=None, call=None, kwargs=None,
name=None,
location=None,
instance_id=None,
call=None,
kwargs=None,
):
"""
Show the console output from the instance.
@ -4862,7 +4872,10 @@ def get_console_output(
def get_password_data(
name=None, kwargs=None, instance_id=None, call=None,
name=None,
kwargs=None,
instance_id=None,
call=None,
):
"""
Return password data for a Windows instance.

View file

@ -270,7 +270,9 @@ def list_nodes_select(call=None):
salt-cloud -S
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)

View file

@ -59,7 +59,9 @@ def get_configured_provider():
Return the first configured instance.
"""
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__, ("key",),
__opts__,
__active_provider_name__ or __virtualname__,
("key",),
)
@ -68,7 +70,8 @@ def get_dependencies():
Warn if dependencies aren't met.
"""
return config.check_driver_dependencies(
__active_provider_name__ or __virtualname__, {"hcloud": HAS_HCLOUD},
__active_provider_name__ or __virtualname__,
{"hcloud": HAS_HCLOUD},
)
@ -222,7 +225,9 @@ def show_instance(name, call=None):
node = {}
__utils__["cloud.cache_node"](
node, __active_provider_name__ or __virtualname__, __opts__,
node,
__active_provider_name__ or __virtualname__,
__opts__,
)
return node
@ -268,7 +273,9 @@ def create(vm_):
"starting create",
"salt/cloud/{}/creating".format(vm_["name"]),
args=__utils__["cloud.filter_event"](
"creating", vm_, ["name", "profile", "provider", "driver"],
"creating",
vm_,
["name", "profile", "provider", "driver"],
),
sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"],
@ -348,7 +355,9 @@ def create(vm_):
"created instance",
"salt/cloud/{}/created".format(vm_["name"]),
args=__utils__["cloud.filter_event"](
"created", vm_, ["name", "profile", "provider", "driver"],
"created",
vm_,
["name", "profile", "provider", "driver"],
),
sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"],
@ -503,7 +512,9 @@ def destroy(name, call=None):
if __opts__.get("update_cachedir", False) is True:
__utils__["cloud.delete_minion_cachedir"](
name, __active_provider_name__.split(":")[0], __opts__,
name,
__active_provider_name__.split(":")[0],
__opts__,
)
return {"Destroyed": "{} was destroyed.".format(name)}

View file

@ -864,7 +864,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)
@ -989,7 +991,10 @@ def show_key(kwargs=None, call=None):
log.error("A keyname is required.")
return False
rcode, data = query(command="my/keys/{}".format(kwargs["keyname"]), method="GET",)
rcode, data = query(
command="my/keys/{}".format(kwargs["keyname"]),
method="GET",
)
return {"keys": {data["name"]: data["key"]}}
@ -1028,7 +1033,11 @@ def import_key(kwargs=None, call=None):
send_data = {"name": kwargs["keyname"], "key": kwargs["key"]}
kwargs["data"] = salt.utils.json.dumps(send_data)
rcode, data = query(command="my/keys", method="POST", data=kwargs["data"],)
rcode, data = query(
command="my/keys",
method="POST",
data=kwargs["data"],
)
log.debug(pprint.pformat(data))
return {"keys": {data["name"]: data["key"]}}
@ -1055,7 +1064,8 @@ def delete_key(kwargs=None, call=None):
return False
rcode, data = query(
command="my/keys/{}".format(kwargs["keyname"]), method="DELETE",
command="my/keys/{}".format(kwargs["keyname"]),
method="DELETE",
)
return data

View file

@ -233,7 +233,11 @@ def list_nodes_select(call=None):
raise SaltCloudSystemExit("query.selection not found in /etc/salt/cloud")
# TODO: somewhat doubt the implementation of cloud.list_nodes_select
return salt.utils.cloud.list_nodes_select(list_nodes_full(), selection, call,)
return salt.utils.cloud.list_nodes_select(
list_nodes_full(),
selection,
call,
)
def to_ip_addr_type(addr_type):

View file

@ -179,7 +179,7 @@ def get_configured_provider():
return config.is_provider_configured(
__opts__,
_get_active_provider_name() or __virtualname__,
("apikey", "password",),
("apikey", "password"),
)
@ -400,82 +400,82 @@ def _warn_for_api_v3():
class LinodeAPI:
@abc.abstractmethod
def avail_images(self):
""" avail_images implementation """
"""avail_images implementation"""
@abc.abstractmethod
def avail_locations(self):
""" avail_locations implementation """
"""avail_locations implementation"""
@abc.abstractmethod
def avail_sizes(self):
""" avail_sizes implementation """
"""avail_sizes implementation"""
@abc.abstractmethod
def boot(self, name=None, kwargs=None):
""" boot implementation """
"""boot implementation"""
@abc.abstractmethod
def clone(self, kwargs=None):
""" clone implementation """
"""clone implementation"""
@abc.abstractmethod
def create_config(self, kwargs=None):
""" create_config implementation """
"""create_config implementation"""
@abc.abstractmethod
def create(self, vm_):
""" create implementation """
"""create implementation"""
@abc.abstractmethod
def destroy(self, name):
""" destroy implementation """
"""destroy implementation"""
@abc.abstractmethod
def get_config_id(self, kwargs=None):
""" get_config_id implementation """
"""get_config_id implementation"""
@abc.abstractmethod
def list_nodes(self):
""" list_nodes implementation """
"""list_nodes implementation"""
@abc.abstractmethod
def list_nodes_full(self):
""" list_nodes_full implementation """
"""list_nodes_full implementation"""
@abc.abstractmethod
def list_nodes_min(self):
""" list_nodes_min implementation """
"""list_nodes_min implementation"""
@abc.abstractmethod
def reboot(self, name):
""" reboot implementation """
"""reboot implementation"""
@abc.abstractmethod
def show_instance(self, name):
""" show_instance implementation """
"""show_instance implementation"""
@abc.abstractmethod
def show_pricing(self, kwargs=None):
""" show_pricing implementation """
"""show_pricing implementation"""
@abc.abstractmethod
def start(self, name):
""" start implementation """
"""start implementation"""
@abc.abstractmethod
def stop(self, name):
""" stop implementation """
"""stop implementation"""
@abc.abstractmethod
def _get_linode_by_name(self, name):
""" _get_linode_by_name implementation """
"""_get_linode_by_name implementation"""
@abc.abstractmethod
def _get_linode_by_id(self, linode_id):
""" _get_linode_by_id implementation """
"""_get_linode_by_id implementation"""
def get_plan_id(self, kwargs=None):
""" get_plan_id implementation """
"""get_plan_id implementation"""
raise SaltCloudSystemExit(
"The get_plan_id is not supported by this api_version."
)
@ -495,7 +495,9 @@ class LinodeAPI:
def list_nodes_select(self, call):
return __utils__["cloud.list_nodes_select"](
self.list_nodes_full(), __opts__["query.selection"], call,
self.list_nodes_full(),
__opts__["query.selection"],
call,
)
@ -1016,7 +1018,12 @@ class LinodeAPIv4(LinodeAPI):
return (public, private)
def _poll(
self, description, getter, condition, timeout=None, poll_interval=None,
self,
description,
getter,
condition,
timeout=None,
poll_interval=None,
):
"""
Return true in handler to signal complete.

View file

@ -448,7 +448,9 @@ def list_nodes_select(conn=None, call=None):
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, "function"), __opts__["query.selection"], call,
list_nodes_full(conn, "function"),
__opts__["query.selection"],
call,
)

View file

@ -338,7 +338,9 @@ def list_nodes_select(call=None):
)
return __utils__["cloud.list_nodes_select"](
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)

View file

@ -513,7 +513,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields.
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__["query.selection"], call,
list_nodes_full(),
__opts__["query.selection"],
call,
)

View file

@ -66,7 +66,11 @@ def get_configured_provider():
return config.is_provider_configured(
__opts__,
_get_active_provider_name() or __virtualname__,
("user", "password", "url",),
(
"user",
"password",
"url",
),
)
@ -148,7 +152,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__["query.selection"], call,
list_nodes_full(),
__opts__["query.selection"],
call,
)

View file

@ -520,7 +520,9 @@ def list_nodes_select(call=None):
salt-cloud -S my-proxmox-config
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__["query.selection"], call,
list_nodes_full(),
__opts__["query.selection"],
call,
)
@ -566,7 +568,9 @@ def _reconfigure_clone(vm_, vmid):
if re.match(r"^(ide|sata|scsi)(\d+)$", setting):
postParams = {setting: vm_[setting]}
query(
"post", "nodes/{}/qemu/{}/config".format(vm_["host"], vmid), postParams,
"post",
"nodes/{}/qemu/{}/config".format(vm_["host"], vmid),
postParams,
)
elif re.match(r"^net(\d+)$", setting):
@ -589,7 +593,9 @@ def _reconfigure_clone(vm_, vmid):
# Convert the dictionary back into a string list
postParams = {setting: _dictionary_to_stringlist(new_setting)}
query(
"post", "nodes/{}/qemu/{}/config".format(vm_["host"], vmid), postParams,
"post",
"nodes/{}/qemu/{}/config".format(vm_["host"], vmid),
postParams,
)
@ -702,7 +708,11 @@ def create(vm_):
ssh_username = config.get_cloud_config_value(
"ssh_username", vm_, __opts__, default="root"
)
ssh_password = config.get_cloud_config_value("password", vm_, __opts__,)
ssh_password = config.get_cloud_config_value(
"password",
vm_,
__opts__,
)
ret["ip_address"] = ip_address
ret["username"] = ssh_username

View file

@ -48,7 +48,11 @@ def get_configured_provider():
return config.is_provider_configured(
__opts__,
_get_active_provider_name() or __virtualname__,
("username", "identity_url", "compute_region",),
(
"username",
"identity_url",
"compute_region",
),
)

View file

@ -596,7 +596,9 @@ def list_nodes_select(call=None):
salt-cloud -S my-qingcloud
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)

View file

@ -61,16 +61,14 @@ def _get_active_provider_name():
def get_configured_provider():
""" Return the first configured instance.
"""
"""Return the first configured instance."""
return config.is_provider_configured(
__opts__, _get_active_provider_name() or __virtualname__, ("token",)
)
def avail_images(call=None):
""" Return a list of the images that are on the provider.
"""
"""Return a list of the images that are on the provider."""
if call == "action":
raise SaltCloudSystemExit(
"The avail_images function must be called with "
@ -88,8 +86,7 @@ def avail_images(call=None):
def list_nodes(call=None):
""" Return a list of the BareMetal servers that are on the provider.
"""
"""Return a list of the BareMetal servers that are on the provider."""
if call == "action":
raise SaltCloudSystemExit(
"The list_nodes function must be called with -f or --function."
@ -124,8 +121,7 @@ def list_nodes(call=None):
def list_nodes_full(call=None):
""" Return a list of the BareMetal servers that are on the provider.
"""
"""Return a list of the BareMetal servers that are on the provider."""
if call == "action":
raise SaltCloudSystemExit(
"list_nodes_full must be called with -f or --function"
@ -144,17 +140,18 @@ def list_nodes_full(call=None):
def list_nodes_select(call=None):
""" Return a list of the BareMetal servers that are on the provider, with
"""Return a list of the BareMetal servers that are on the provider, with
select fields.
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)
def get_image(server_):
""" Return the image object to use.
"""
"""Return the image object to use."""
images = avail_images()
server_image = str(
config.get_cloud_config_value("image", server_, __opts__, search_global=False)
@ -168,8 +165,7 @@ def get_image(server_):
def create_node(args):
""" Create a node.
"""
"""Create a node."""
node = query(method="servers", args=args, http_method="POST")
action = query(
@ -269,8 +265,7 @@ def create(server_):
return False
def __query_node_data(server_name):
""" Called to check if the server has a public IP address.
"""
"""Called to check if the server has a public IP address."""
data = show_instance(server_name, "action")
if data and data.get("public_ip"):
return data
@ -332,8 +327,7 @@ def query(
http_method="GET",
root="api_root",
):
""" Make a call to the Scaleway API.
"""
"""Make a call to the Scaleway API."""
if root == "api_root":
default_url = "https://cp-par1.scaleway.com"
@ -344,7 +338,11 @@ def query(
base_path = str(
config.get_cloud_config_value(
root, vm_, __opts__, search_global=False, default=default_url,
root,
vm_,
__opts__,
search_global=False,
default=default_url,
)
)
@ -387,8 +385,7 @@ def query(
def script(server_):
""" Return the script deployment object.
"""
"""Return the script deployment object."""
return salt.utils.cloud.os_script(
config.get_cloud_config_value("script", server_, __opts__),
server_,
@ -400,8 +397,7 @@ def script(server_):
def show_instance(name, call=None):
""" Show the details from a Scaleway BareMetal server.
"""
"""Show the details from a Scaleway BareMetal server."""
if call != "action":
raise SaltCloudSystemExit(
"The show_instance action must be called with -a or --action."
@ -427,7 +423,7 @@ def _get_node(name):
def destroy(name, call=None):
""" Destroy a node. Will check termination protection and warn if enabled.
"""Destroy a node. Will check termination protection and warn if enabled.
CLI Example:

View file

@ -582,7 +582,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__["query.selection"], call,
list_nodes_full(),
__opts__["query.selection"],
call,
)

View file

@ -477,7 +477,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__["query.selection"], call,
list_nodes_full(),
__opts__["query.selection"],
call,
)

View file

@ -379,7 +379,9 @@ def list_nodes_select(call=None):
salt-cloud -S
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)

View file

@ -60,8 +60,8 @@ def avail_locations(call=None):
def avail_images(call=None):
"""This function returns a list of images available for this cloud provider.
vagrant will return a list of profiles.
salt-cloud --list-images my-cloud-provider
vagrant will return a list of profiles.
salt-cloud --list-images my-cloud-provider
"""
vm_ = get_configured_provider()
return {"Profiles": [profile for profile in vm_["profiles"]]}
@ -175,7 +175,9 @@ def list_nodes_select(call=None):
select fields.
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)

View file

@ -328,7 +328,9 @@ def list_nodes(kwargs=None, call=None):
"public_ips",
]
return __utils__["cloud.list_nodes_select"](
list_nodes_full("function"), attributes, call,
list_nodes_full("function"),
attributes,
call,
)
@ -337,7 +339,9 @@ def list_nodes_select(call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__["cloud.list_nodes_select"](
list_nodes_full("function"), __opts__["query.selection"], call,
list_nodes_full("function"),
__opts__["query.selection"],
call,
)

View file

@ -191,7 +191,11 @@ def get_configured_provider():
return config.is_provider_configured(
__opts__,
_get_active_provider_name() or __virtualname__,
("url", "user", "password",),
(
"url",
"user",
"password",
),
)
@ -432,8 +436,10 @@ def _edit_existing_network_adapter(
else:
# If switch type not specified or does not match, show error and return
if not switch_type:
err_msg = "The switch type to be used by '{}' has not been specified".format(
network_adapter.deviceInfo.label
err_msg = (
"The switch type to be used by '{}' has not been specified".format(
network_adapter.deviceInfo.label
)
)
else:
err_msg = "Cannot create '{}'. Invalid/unsupported switch type '{}'".format(
@ -519,8 +525,10 @@ def _add_new_network_adapter_helper(
else:
# If switch type not specified or does not match, show error and return
if not switch_type:
err_msg = "The switch type to be used by '{}' has not been specified".format(
network_adapter_label
err_msg = (
"The switch type to be used by '{}' has not been specified".format(
network_adapter_label
)
)
else:
err_msg = "Cannot create '{}'. Invalid/unsupported switch type '{}'".format(
@ -3151,8 +3159,10 @@ def create(vm_):
)
# get recommended datastores
recommended_datastores = si.content.storageResourceManager.RecommendDatastores(
storageSpec=storage_spec
recommended_datastores = (
si.content.storageResourceManager.RecommendDatastores(
storageSpec=storage_spec
)
)
# apply storage DRS recommendations
@ -4369,7 +4379,9 @@ def add_host(kwargs=None, call=None):
raise SaltCloudSystemExit("Specified datacenter does not exist.")
spec = vim.host.ConnectSpec(
hostName=host_name, userName=host_user, password=host_password,
hostName=host_name,
userName=host_user,
password=host_password,
)
if host_ssl_thumbprint:

View file

@ -264,7 +264,9 @@ def list_nodes_select(conn=None, call=None):
Return a list of the VMs that are on the provider, with select fields
"""
return __utils__["cloud.list_nodes_select"](
list_nodes_full(), __opts__["query.selection"], call,
list_nodes_full(),
__opts__["query.selection"],
call,
)
@ -342,7 +344,11 @@ def create(vm_):
vm_["driver"] = vm_["provider"]
private_networking = config.get_cloud_config_value(
"enable_private_network", vm_, __opts__, search_global=False, default=False,
"enable_private_network",
vm_,
__opts__,
search_global=False,
default=False,
)
ssh_key_ids = config.get_cloud_config_value(
@ -350,7 +356,11 @@ def create(vm_):
)
startup_script = config.get_cloud_config_value(
"startup_script_id", vm_, __opts__, search_global=False, default=None,
"startup_script_id",
vm_,
__opts__,
search_global=False,
default=None,
)
if startup_script and str(startup_script) not in avail_scripts():
@ -361,7 +371,11 @@ def create(vm_):
return False
firewall_group_id = config.get_cloud_config_value(
"firewall_group_id", vm_, __opts__, search_global=False, default=None,
"firewall_group_id",
vm_,
__opts__,
search_global=False,
default=None,
)
if firewall_group_id and str(firewall_group_id) not in avail_firewall_groups():
@ -598,7 +612,10 @@ def _query(path, method="GET", data=None, params=None, header_dict=None, decode=
Perform a query directly against the Vultr REST API
"""
api_key = config.get_cloud_config_value(
"api_key", get_configured_provider(), __opts__, search_global=False,
"api_key",
get_configured_provider(),
__opts__,
search_global=False,
)
management_host = config.get_cloud_config_value(
"management_host",
@ -608,7 +625,9 @@ def _query(path, method="GET", data=None, params=None, header_dict=None, decode=
default="api.vultr.com",
)
url = "https://{management_host}/v1/{path}?api_key={api_key}".format(
management_host=management_host, path=path, api_key=api_key,
management_host=management_host,
path=path,
api_key=api_key,
)
if header_dict is None:

View file

@ -342,7 +342,9 @@ def list_nodes_select(call=None):
"""
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__["query.selection"], call,
list_nodes_full(),
__opts__["query.selection"],
call,
)

View file

@ -696,7 +696,9 @@ class SlackClient:
except (StopIteration, AttributeError):
outputter = None
return salt.output.string_format(
{x: y["return"] for x, y in data.items()}, out=outputter, opts=__opts__,
{x: y["return"] for x, y in data.items()},
out=outputter,
opts=__opts__,
)
except Exception as exc: # pylint: disable=broad-except
import pprint
@ -826,11 +828,13 @@ class SlackClient:
this_job = outstanding[jid]
channel = self.sc.server.channels.find(this_job["channel"])
return_text = self.format_return_text(result, function)
return_prefix = "@{}'s job `{}` (id: {}) (target: {}) returned".format(
this_job["user_name"],
this_job["cmdline"],
jid,
this_job["target"],
return_prefix = (
"@{}'s job `{}` (id: {}) (target: {}) returned".format(
this_job["user_name"],
this_job["cmdline"],
jid,
this_job["target"],
)
)
channel.send_message(return_prefix)
ts = time.time()
@ -901,7 +905,11 @@ class SlackClient:
# according to https://github.com/saltstack/salt-api/issues/164, tgt_type has changed to expr_form
with salt.client.LocalClient() as local:
job_id = local.cmd_async(
str(target), cmd, arg=args, kwarg=kwargs, tgt_type=str(tgt_type),
str(target),
cmd,
arg=args,
kwarg=kwargs,
tgt_type=str(tgt_type),
)
log.info("ret from local.cmd_async is %s", job_id)
return job_id

View file

@ -230,9 +230,10 @@ def execute(context=None, lens=None, commands=(), load_path=None):
# if command.split fails arg will not be set
if "arg" not in locals():
arg = command
ret["error"] = (
"Invalid formatted command, "
"see debug log for details: {}".format(arg)
ret[
"error"
] = "Invalid formatted command, " "see debug log for details: {}".format(
arg
)
return ret
@ -488,7 +489,7 @@ def ls(path, load_path=None): # pylint: disable=C0103
"""
def _match(path):
""" Internal match function """
"""Internal match function"""
try:
matches = aug.match(salt.utils.stringutils.to_str(path))
except RuntimeError:

View file

@ -179,7 +179,10 @@ def update_employee(emp_id, key=None, value=None, items=None):
xml_items = "<employee>{}</employee>".format(xml_items)
status, result = _query(
action="employees", command=emp_id, data=xml_items, method="POST",
action="employees",
command=emp_id,
data=xml_items,
method="POST",
)
return show_employee(emp_id, ",".join(items.keys()))

View file

@ -1601,8 +1601,10 @@ def create_virtual(
elif vlans["disabled"]:
payload["vlans-disabled"] = True
except Exception: # pylint: disable=broad-except
return "Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format(
vlans=vlans
return (
"Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format(
vlans=vlans
)
)
elif vlans == "none":
payload["vlans"] = "none"
@ -1888,8 +1890,10 @@ def modify_virtual(
elif vlans["disabled"]:
payload["vlans-disabled"] = True
except Exception: # pylint: disable=broad-except
return "Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format(
vlans=vlans
return (
"Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format(
vlans=vlans
)
)
elif vlans == "none":
payload["vlans"] = "none"
@ -1967,7 +1971,11 @@ def delete_virtual(hostname, username, password, name):
def list_monitor(
hostname, username, password, monitor_type, name=None,
hostname,
username,
password,
monitor_type,
name=None,
):
"""
A function to connect to a bigip device and list an existing monitor. If no name is provided than all
@ -2163,7 +2171,11 @@ def delete_monitor(hostname, username, password, monitor_type, name):
def list_profile(
hostname, username, password, profile_type, name=None,
hostname,
username,
password,
profile_type,
name=None,
):
"""
A function to connect to a bigip device and list an existing profile. If no name is provided than all

View file

@ -80,7 +80,12 @@ def __virtual__():
def _list_distributions(
conn, name=None, region=None, key=None, keyid=None, profile=None,
conn,
name=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Private function that returns an iterator over all CloudFront distributions.
@ -185,7 +190,12 @@ def get_distribution(name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
for _, dist in _list_distributions(
conn, name=name, region=region, key=key, keyid=keyid, profile=profile,
conn,
name=name,
region=region,
key=key,
keyid=keyid,
profile=profile,
):
# _list_distributions should only return the one distribution
# that we want (with the given name).
@ -231,7 +241,11 @@ def export_distributions(region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
for name, distribution in _list_distributions(
conn, region=region, key=key, keyid=keyid, profile=profile,
conn,
region=region,
key=key,
keyid=keyid,
profile=profile,
):
config = distribution["distribution"]["DistributionConfig"]
tags = distribution["tags"]
@ -250,11 +264,21 @@ def export_distributions(region=None, key=None, keyid=None, profile=None):
log.trace("Boto client error: {}", exc)
dumper = __utils__["yaml.get_dumper"]("IndentedSafeOrderedDumper")
return __utils__["yaml.dump"](results, default_flow_style=False, Dumper=dumper,)
return __utils__["yaml.dump"](
results,
default_flow_style=False,
Dumper=dumper,
)
def create_distribution(
name, config, tags=None, region=None, key=None, keyid=None, profile=None,
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Create a CloudFront distribution with the given name, config, and (optionally) tags.
@ -318,7 +342,13 @@ def create_distribution(
def update_distribution(
name, config, tags=None, region=None, key=None, keyid=None, profile=None,
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Update the config (and optionally tags) for the CloudFront distribution with the given name.
@ -372,7 +402,9 @@ def update_distribution(
try:
if "old" in config_diff or "new" in config_diff:
conn.update_distribution(
DistributionConfig=config, Id=current_distribution["Id"], IfMatch=etag,
DistributionConfig=config,
Id=current_distribution["Id"],
IfMatch=etag,
)
if tags:
arn = current_distribution["ARN"]
@ -383,14 +415,16 @@ def update_distribution(
],
}
conn.tag_resource(
Resource=arn, Tags=tags_to_add,
Resource=arn,
Tags=tags_to_add,
)
if "old" in tags_diff:
tags_to_remove = {
"Items": list(tags_diff["old"].keys()),
}
conn.untag_resource(
Resource=arn, TagKeys=tags_to_remove,
Resource=arn,
TagKeys=tags_to_remove,
)
except botocore.exceptions.ClientError as err:
return {"error": __utils__["boto3.get_error"](err)}

View file

@ -67,7 +67,9 @@ def create_pipeline(
r = {}
try:
response = client.create_pipeline(
name=name, uniqueId=unique_id, description=description,
name=name,
uniqueId=unique_id,
description=description,
)
r["result"] = response["pipelineId"]
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
@ -130,7 +132,8 @@ def get_pipeline_definition(
r = {}
try:
r["result"] = client.get_pipeline_definition(
pipelineId=pipeline_id, version=version,
pipelineId=pipeline_id,
version=version,
)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r["error"] = str(e)
@ -255,5 +258,7 @@ def _get_session(region, key, keyid, profile):
region = "us-east-1"
return boto3.session.Session(
region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid,
region_name=region,
aws_secret_access_key=key,
aws_access_key_id=keyid,
)

View file

@ -252,7 +252,7 @@ def zone_exists(
error_retries=5,
):
"""
Check for the existence of a Route53 hosted zone.
Check for the existence of a Route53 hosted zone.
.. versionadded:: 2015.8.0
@ -262,7 +262,7 @@ def zone_exists(
salt myminion boto_route53.zone_exists example.org
retry_on_errors
retry_on_errors
Continue to query if the zone exists after an error is
raised. The previously used argument `retry_on_rate_limit`
was deprecated for this argument. Users can still use
@ -277,7 +277,6 @@ def zone_exists(
`rate_limit_retries` to ensure backwards compatibility,
but please migrate to using the favored `error_retries`
argument instead.
"""
if region is None:
region = "universal"
@ -546,7 +545,7 @@ def get_record(
error_retries=5,
):
"""
Get a record from a zone.
Get a record from a zone.
CLI Example:
@ -554,7 +553,7 @@ def get_record(
salt myminion boto_route53.get_record test.example.org example.org A
retry_on_errors
retry_on_errors
Continue to query if the zone exists after an error is
raised. The previously used argument `retry_on_rate_limit`
was deprecated for this argument. Users can still use
@ -657,7 +656,7 @@ def add_record(
error_retries=5,
):
"""
Add a record to a zone.
Add a record to a zone.
CLI Example:
@ -665,7 +664,7 @@ def add_record(
salt myminion boto_route53.add_record test.example.org 1.1.1.1 example.org A
retry_on_errors
retry_on_errors
Continue to query if the zone exists after an error is
raised. The previously used argument `retry_on_rate_limit`
was deprecated for this argument. Users can still use
@ -764,15 +763,15 @@ def update_record(
error_retries=5,
):
"""
Modify a record in a zone.
Modify a record in a zone.
CLI Example:
CLI Example:
.. code-block:: bash
.. code-block:: bash
salt myminion boto_route53.modify_record test.example.org 1.1.1.1 example.org A
salt myminion boto_route53.modify_record test.example.org 1.1.1.1 example.org A
retry_on_errors
retry_on_errors
Continue to query if the zone exists after an error is
raised. The previously used argument `retry_on_rate_limit`
was deprecated for this argument. Users can still use
@ -853,15 +852,15 @@ def delete_record(
error_retries=5,
):
"""
Modify a record in a zone.
Modify a record in a zone.
CLI Example:
CLI Example:
.. code-block:: bash
.. code-block:: bash
salt myminion boto_route53.delete_record test.example.org example.org A
salt myminion boto_route53.delete_record test.example.org example.org A
retry_on_errors
retry_on_errors
Continue to query if the zone exists after an error is
raised. The previously used argument `retry_on_rate_limit`
was deprecated for this argument. Users can still use

View file

@ -85,7 +85,12 @@ def __init__(opts): # pylint: disable=unused-argument
def get_object_metadata(
name, extra_args=None, region=None, key=None, keyid=None, profile=None,
name,
extra_args=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Get metadata about an S3 object.
@ -121,7 +126,13 @@ def get_object_metadata(
def upload_file(
source, name, extra_args=None, region=None, key=None, keyid=None, profile=None,
source,
name,
extra_args=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Upload a local file as an S3 object.

View file

@ -118,7 +118,12 @@ def exists(name, region=None, key=None, keyid=None, profile=None):
def create(
name, attributes=None, region=None, key=None, keyid=None, profile=None,
name,
attributes=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Create an SQS queue.
@ -210,7 +215,12 @@ def get_attributes(name, region=None, key=None, keyid=None, profile=None):
def set_attributes(
name, attributes, region=None, key=None, keyid=None, profile=None,
name,
attributes,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Set attributes on an SQS queue.

View file

@ -196,7 +196,12 @@ def __init__(opts):
def check_vpc(
vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Check whether a VPC with the given name or id exists.
@ -672,7 +677,13 @@ def _get_id(
def get_id(
name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None,
name=None,
cidr=None,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given VPC properties, return the VPC id if a match is found.
@ -883,7 +894,12 @@ def delete(
def describe(
vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Describe a VPC's properties. If no VPC ID/Name is spcified then describe the default VPC.

View file

@ -660,8 +660,10 @@ def set_hostname(hostname=None):
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{}" ></mgmtIf>""".format(
hostname
inconfig = (
"""<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{}" ></mgmtIf>""".format(
hostname
)
)
ret = __proxy__["cimc.set_config_modify"](dn, inconfig, False)

View file

@ -54,8 +54,7 @@ def __virtual__():
def _get_ccp(config=None, config_path=None, saltenv="base"):
"""
"""
""" """
if config_path:
config = __salt__["cp.get_file_str"](config_path, saltenv=saltenv)
if config is False:
@ -257,7 +256,7 @@ def find_lines_w_child(
salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits'
salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+'
"""
"""
lines = find_objects_w_child(
config=config,
config_path=config_path,
@ -323,7 +322,7 @@ def find_objects_wo_child(
child_regex='stopbits')
for obj in objects:
print(obj.text)
"""
"""
ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)
lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws)
return lines

View file

@ -226,7 +226,10 @@ def createsuperuser(
salt '*' django.createsuperuser <settings_module> user user@example.com
"""
args = ["noinput"]
kwargs = dict(email=email, username=username,)
kwargs = dict(
email=email,
username=username,
)
if database:
kwargs["database"] = database
return command(

View file

@ -117,8 +117,10 @@ def route_create(
packet to instance "instance-1"(if packet is intended to other network)
"""
credentials = oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name(
credential_file
credentials = (
oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name(
credential_file
)
)
service = googleapiclient.discovery.build("compute", "v1", credentials=credentials)
routes = service.routes()

View file

@ -180,7 +180,10 @@ def bootstrap(
if platform in ("rpm", "yum"):
_bootstrap_yum(
root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url,
root,
pkgs=pkgs,
exclude_pkgs=exclude_pkgs,
epel_url=epel_url,
)
elif platform == "deb":
_bootstrap_deb(
@ -194,7 +197,10 @@ def bootstrap(
)
elif platform == "pacman":
_bootstrap_pacman(
root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs,
root,
img_format=img_format,
pkgs=pkgs,
exclude_pkgs=exclude_pkgs,
)
if img_format != "dir":
@ -285,7 +291,11 @@ def _populate_cache(platform, pkg_cache, mount_dir):
def _bootstrap_yum(
root, pkg_confs="/etc/yum*", pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL,
root,
pkg_confs="/etc/yum*",
pkgs=None,
exclude_pkgs=None,
epel_url=EPEL_URL,
):
"""
Bootstrap an image using the yum tools
@ -364,7 +374,13 @@ def _bootstrap_yum(
def _bootstrap_deb(
root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None,
root,
arch,
flavor,
repo_url=None,
static_qemu=None,
pkgs=None,
exclude_pkgs=None,
):
"""
Bootstrap an image using the Debian tools
@ -452,7 +468,11 @@ def _bootstrap_deb(
def _bootstrap_pacman(
root, pkg_confs="/etc/pacman*", img_format="dir", pkgs=None, exclude_pkgs=None,
root,
pkg_confs="/etc/pacman*",
img_format="dir",
pkgs=None,
exclude_pkgs=None,
):
"""
Bootstrap an image using the pacman tools
@ -618,7 +638,10 @@ def _tar(name, root, path=None, compress="bzip2"):
tarfile = "{}/{}.tar.{}".format(path, name, ext)
out = __salt__["archive.tar"](
options="{}pcf".format(compression), tarfile=tarfile, sources=".", dest=root,
options="{}pcf".format(compression),
tarfile=tarfile,
sources=".",
dest=root,
)
@ -642,7 +665,9 @@ def _untar(name, dest=None, path=None, compress="bz2"):
tarfile = "{}/{}.tar.{}".format(path, name, ext)
out = __salt__["archive.tar"](
options="{}xf".format(compression), tarfile=tarfile, dest=dest,
options="{}xf".format(compression),
tarfile=tarfile,
dest=dest,
)

View file

@ -68,7 +68,10 @@ def _gluster_xml(cmd):
# We will pass the command string as stdin to allow for much longer
# command strings. This is especially useful for creating large volumes
# where the list of bricks exceeds 128 characters.
if _get_version() < (3, 6,):
if _get_version() < (
3,
6,
):
result = __salt__["cmd.run"](
'script -q -c "gluster --xml --mode=script"', stdin="{}\n\004".format(cmd)
)
@ -767,7 +770,10 @@ def get_max_op_version():
salt '*' glusterfs.get_max_op_version
"""
if _get_version() < (3, 10,):
if _get_version() < (
3,
10,
):
return (
False,
"Glusterfs version must be 3.10+. Your version is {}.".format(

View file

@ -28,16 +28,16 @@ def __virtual__():
def _hadoop_cmd(module, command, *args):
"""
Hadoop/hdfs command wrapper
Hadoop/hdfs command wrapper
As Hadoop command has been deprecated this module will default
to use hdfs command and fall back to hadoop if it is not found
As Hadoop command has been deprecated this module will default
to use hdfs command and fall back to hadoop if it is not found
In order to prevent random execution the module name is checked
In order to prevent random execution the module name is checked
Follows hadoop command template:
hadoop module -command args
E.g.: hadoop dfs -ls /
Follows hadoop command template:
hadoop module -command args
E.g.: hadoop dfs -ls /
"""
tool = "hadoop"
if salt.utils.path.which("hdfs"):

View file

@ -637,7 +637,7 @@ def create_continuous_query(
.. code-block:: bash
salt '*' influxdb.create_continuous_query mydb cq_month 'SELECT mean(*) INTO mydb.a_month.:MEASUREMENT FROM mydb.a_week./.*/ GROUP BY time(5m), *' """
salt '*' influxdb.create_continuous_query mydb cq_month 'SELECT mean(*) INTO mydb.a_month.:MEASUREMENT FROM mydb.a_week./.*/ GROUP BY time(5m), *'"""
client = _client(**client_args)
full_query = "CREATE CONTINUOUS QUERY {name} ON {database}"
if resample_time:

View file

@ -257,7 +257,10 @@ class Inspector(EnvLoader):
for p_type, p_list in (
("f", files),
("d", directories),
("l", links,),
(
"l",
links,
),
):
for p_obj in p_list:
stats = os.stat(p_obj)
@ -415,7 +418,12 @@ class Inspector(EnvLoader):
all_links.extend(e_links)
return self._get_unmanaged_files(
self._get_managed_files(), (all_files, all_dirs, all_links,)
self._get_managed_files(),
(
all_files,
all_dirs,
all_links,
),
)
def _prepare_full_scan(self, **kwargs):

View file

@ -52,7 +52,7 @@ def status(jboss_config, host=None, server_config=None):
salt '*' jboss7.status '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
"""
"""
log.debug("======================== MODULE FUNCTION: jboss7.status")
if host is None and server_config is None:
operation = ":read-attribute(name=server-state)"
@ -85,7 +85,7 @@ def stop_server(jboss_config, host=None):
salt '*' jboss7.stop_server '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
"""
"""
log.debug("======================== MODULE FUNCTION: jboss7.stop_server")
if host is None:
operation = ":shutdown"
@ -124,7 +124,7 @@ def reload_(jboss_config, host=None):
salt '*' jboss7.reload '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
"""
"""
log.debug("======================== MODULE FUNCTION: jboss7.reload")
if host is None:
operation = ":reload"
@ -306,8 +306,10 @@ def __get_datasource_resource_description(jboss_config, name, profile=None):
profile,
)
operation = '/subsystem=datasources/data-source="{name}":read-resource-description'.format(
name=name
operation = (
'/subsystem=datasources/data-source="{name}":read-resource-description'.format(
name=name
)
)
if profile is not None:
operation = '/profile="{profile}"'.format(profile=profile) + operation
@ -332,7 +334,7 @@ def read_datasource(jboss_config, name, profile=None):
.. code-block:: bash
salt '*' jboss7.read_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
"""
"""
log.debug(
"======================== MODULE FUNCTION: jboss7.read_datasource, name=%s",
name,
@ -394,7 +396,7 @@ def update_simple_binding(jboss_config, binding_name, value, profile=None):
.. code-block:: bash
salt '*' jboss7.update_simple_binding '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_binding_name my_binding_value
"""
"""
log.debug(
"======================== MODULE FUNCTION: jboss7.update_simple_binding, binding_name=%s, value=%s, profile=%s",
binding_name,
@ -425,7 +427,7 @@ def read_simple_binding(jboss_config, binding_name, profile=None):
.. code-block:: bash
salt '*' jboss7.read_simple_binding '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_binding_name
"""
"""
log.debug(
"======================== MODULE FUNCTION: jboss7.read_simple_binding, %s",
binding_name,
@ -502,7 +504,7 @@ def remove_datasource(jboss_config, name, profile=None):
.. code-block:: bash
salt '*' jboss7.remove_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_datasource_name
"""
"""
log.debug(
"======================== MODULE FUNCTION: jboss7.remove_datasource, name=%s, profile=%s",
name,
@ -532,7 +534,7 @@ def deploy(jboss_config, source_file):
.. code-block:: bash
salt '*' jboss7.deploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' /opt/deploy_files/my_deploy
"""
"""
log.debug(
"======================== MODULE FUNCTION: jboss7.deploy, source_file=%s",
source_file,
@ -556,7 +558,7 @@ def list_deployments(jboss_config):
salt '*' jboss7.list_deployments '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
"""
"""
log.debug("======================== MODULE FUNCTION: jboss7.list_deployments")
command_result = __salt__["jboss7_cli.run_command"](jboss_config, "deploy")
deployments = []
@ -580,7 +582,7 @@ def undeploy(jboss_config, deployment):
.. code-block:: bash
salt '*' jboss7.undeploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_deployment
"""
"""
log.debug(
"======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s",
deployment,

View file

@ -63,7 +63,7 @@ def _guess_apiserver(apiserver_url=None):
def _kpost(url, data):
""" create any object in kubernetes based on URL """
"""create any object in kubernetes based on URL"""
# Prepare headers
headers = {"Content-Type": "application/json"}
@ -80,7 +80,7 @@ def _kpost(url, data):
def _kput(url, data):
""" put any object in kubernetes based on URL """
"""put any object in kubernetes based on URL"""
# Prepare headers
headers = {"Content-Type": "application/json"}
@ -96,7 +96,7 @@ def _kput(url, data):
def _kpatch(url, data):
""" patch any object in kubernetes based on URL """
"""patch any object in kubernetes based on URL"""
# Prepare headers
headers = {"Content-Type": "application/json-patch+json"}
@ -126,8 +126,8 @@ def _kname(obj):
def _is_dns_subdomain(name):
""" Check that name is DNS subdomain: One or more lowercase rfc1035/rfc1123
labels separated by '.' with a maximum length of 253 characters """
"""Check that name is DNS subdomain: One or more lowercase rfc1035/rfc1123
labels separated by '.' with a maximum length of 253 characters"""
dns_subdomain = re.compile(r"""^[a-z0-9\.-]{1,253}$""")
if dns_subdomain.match(name):
@ -139,10 +139,10 @@ def _is_dns_subdomain(name):
def _is_port_name(name):
""" Check that name is IANA service: An alphanumeric (a-z, and 0-9) string,
"""Check that name is IANA service: An alphanumeric (a-z, and 0-9) string,
with a maximum length of 15 characters, with the '-' character allowed
anywhere except the first or the last character or adjacent to another '-'
character, it must contain at least a (a-z) character """
character, it must contain at least a (a-z) character"""
port_name = re.compile("""^[a-z0-9]{1,15}$""")
if port_name.match(name):
@ -152,10 +152,10 @@ def _is_port_name(name):
def _is_dns_label(name):
""" Check that name is DNS label: An alphanumeric (a-z, and 0-9) string,
"""Check that name is DNS label: An alphanumeric (a-z, and 0-9) string,
with a maximum length of 63 characters, with the '-' character allowed
anywhere except the first or last character, suitable for use as a hostname
or segment in a domain name """
or segment in a domain name"""
dns_label = re.compile(r"""^[a-z0-9][a-z0-9\.-]{1,62}$""")
if dns_label.match(name):
@ -396,7 +396,7 @@ def _get_namespaces(apiserver_url, name=""):
def _create_namespace(namespace, apiserver_url):
""" create namespace on the defined k8s cluster """
"""create namespace on the defined k8s cluster"""
# Prepare URL
url = "{}/api/v1/namespaces".format(apiserver_url)
# Prepare data
@ -507,7 +507,7 @@ def _update_secret(namespace, name, data, apiserver_url):
def _create_secret(namespace, name, data, apiserver_url):
""" create namespace on the defined k8s cluster """
"""create namespace on the defined k8s cluster"""
# Prepare URL
url = "{}/api/v1/namespaces/{}/secrets".format(apiserver_url, namespace)
# Prepare data

View file

@ -1630,17 +1630,20 @@ def init(
run(name, "rm -f '{}'".format(SEED_MARKER), path=path, python_shell=False)
gid = "/.lxc.initial_seed"
gids = [gid, "/lxc.initial_seed"]
if any(
retcode(
name,
"test -e {}".format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True,
if (
any(
retcode(
name,
"test -e {}".format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True,
)
== 0
for x in gids
)
== 0
for x in gids
) or not ret.get("result", True):
or not ret.get("result", True)
):
pass
elif seed or seed_cmd:
if seed:
@ -4373,7 +4376,10 @@ def write_conf(conf_file, conf):
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(line[key], (str, (str,), (int,), float),):
if isinstance(
line[key],
(str, (str,), (int,), float),
):
out_line = " = ".join((key, "{}".format(line[key])))
elif isinstance(line[key], dict):
out_line = " = ".join((key, line[key]["value"]))

File diff suppressed because it is too large Load diff

View file

@ -59,7 +59,9 @@ def apps():
salt marathon-minion-id marathon.apps
"""
response = salt.utils.http.query(
"{}/v2/apps".format(_base_url()), decode_type="json", decode=True,
"{}/v2/apps".format(_base_url()),
decode_type="json",
decode=True,
)
return {"apps": [app["id"] for app in response["dict"]["apps"]]}
@ -88,7 +90,9 @@ def app(id):
salt marathon-minion-id marathon.app my-app
"""
response = salt.utils.http.query(
"{}/v2/apps/{}".format(_base_url(), id), decode_type="json", decode=True,
"{}/v2/apps/{}".format(_base_url(), id),
decode_type="json",
decode=True,
)
return response["dict"]
@ -159,7 +163,9 @@ def info():
salt marathon-minion-id marathon.info
"""
response = salt.utils.http.query(
"{}/v2/info".format(_base_url()), decode_type="json", decode=True,
"{}/v2/info".format(_base_url()),
decode_type="json",
decode=True,
)
return response["dict"]

View file

@ -55,29 +55,29 @@ def get_latest_snapshot(
password=None,
):
"""
Gets latest snapshot of the given artifact
Gets latest snapshot of the given artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
log.debug(
"======================== MODULE FUNCTION: nexus.get_latest_snapshot, nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, target_dir=%s, classifier=%s)",
nexus_url,
@ -132,31 +132,31 @@ def get_snapshot(
password=None,
):
"""
Gets snapshot of the desired version of the artifact
Gets snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
log.debug(
"======================== MODULE FUNCTION: nexus.get_snapshot(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)",
nexus_url,
@ -201,27 +201,27 @@ def get_snapshot_version_string(
password=None,
):
"""
Gets the specific version string of a snapshot of the desired version of the artifact
Gets the specific version string of a snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
log.debug(
"======================== MODULE FUNCTION: nexus.get_snapshot_version_string(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, classifier=%s)",
nexus_url,
@ -262,29 +262,29 @@ def get_latest_release(
password=None,
):
"""
Gets the latest release of the artifact
Gets the latest release of the artifact
nexus_url
URL of nexus instance
repository
Release repository in nexus to retrieve artifact from, for example: libs-releases
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
nexus_url
URL of nexus instance
repository
Release repository in nexus to retrieve artifact from, for example: libs-releases
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
log.debug(
"======================== MODULE FUNCTION: nexus.get_latest_release(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, target_dir=%s, classifier=%s)",
nexus_url,
@ -330,31 +330,31 @@ def get_release(
password=None,
):
"""
Gets the specified release of the artifact
Gets the specified release of the artifact
nexus_url
URL of nexus instance
repository
Release repository in nexus to retrieve artifact from, for example: libs-releases
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
nexus_url
URL of nexus instance
repository
Release repository in nexus to retrieve artifact from, for example: libs-releases
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
"""
log.debug(
"======================== MODULE FUNCTION: nexus.get_release(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)",
nexus_url,
@ -507,11 +507,13 @@ def _get_release_url(
def _get_artifact_metadata_url(nexus_url, repository, group_id, artifact_id):
group_url = __get_group_id_subpath(group_id)
# for released versions the suffix for the file is same as version
artifact_metadata_url = "{nexus_url}/{repository}/{group_url}/{artifact_id}/maven-metadata.xml".format(
nexus_url=nexus_url,
repository=repository,
group_url=group_url,
artifact_id=artifact_id,
artifact_metadata_url = (
"{nexus_url}/{repository}/{group_url}/{artifact_id}/maven-metadata.xml".format(
nexus_url=nexus_url,
repository=repository,
group_url=group_url,
artifact_id=artifact_id,
)
)
log.debug("artifact_metadata_url=%s", artifact_metadata_url)
return artifact_metadata_url

View file

@ -98,12 +98,14 @@ def _get_technologies():
tech = ""
technologies = pyconnman.ConnManager().get_technologies()
for path, params in technologies:
tech += "{}\n\tName = {}\n\tType = {}\n\tPowered = {}\n\tConnected = {}\n".format(
path,
params["Name"],
params["Type"],
params["Powered"] == 1,
params["Connected"] == 1,
tech += (
"{}\n\tName = {}\n\tType = {}\n\tPowered = {}\n\tConnected = {}\n".format(
path,
params["Name"],
params["Type"],
params["Powered"] == 1,
params["Connected"] == 1,
)
)
return tech

View file

@ -41,7 +41,11 @@ def get_users(profile="pagerduty", subdomain=None, api_key=None):
"""
return _list_items(
"users", "id", profile=profile, subdomain=subdomain, api_key=api_key,
"users",
"id",
profile=profile,
subdomain=subdomain,
api_key=api_key,
)
@ -57,7 +61,11 @@ def get_services(profile="pagerduty", subdomain=None, api_key=None):
"""
return _list_items(
"services", "id", profile=profile, subdomain=subdomain, api_key=api_key,
"services",
"id",
profile=profile,
subdomain=subdomain,
api_key=api_key,
)
@ -73,7 +81,11 @@ def get_schedules(profile="pagerduty", subdomain=None, api_key=None):
"""
return _list_items(
"schedules", "id", profile=profile, subdomain=subdomain, api_key=api_key,
"schedules",
"id",
profile=profile,
subdomain=subdomain,
api_key=api_key,
)

View file

@ -638,13 +638,13 @@ def get_ha_config():
def get_ha_link():
"""
Show high-availability link-monitoring state.
Show high-availability link-monitoring state.
CLI Example:
CLI Example:
.. code-block:: bash
.. code-block:: bash
salt '*' panos.get_ha_link
salt '*' panos.get_ha_link
"""
query = {
@ -1510,7 +1510,10 @@ def get_zones(vsys="1"):
def install_antivirus(
version=None, latest=False, synch=False, skip_commit=False,
version=None,
latest=False,
synch=False,
skip_commit=False,
):
"""
Install anti-virus packages.

View file

@ -380,7 +380,8 @@ def modify(
for change in changes:
cmds.append(
"{flag}{value}".format(
flag=flags[change], value=shlex.quote(changes[change]),
flag=flags[change],
value=shlex.quote(changes[change]),
)
)
if reset_login_hours:
@ -390,7 +391,8 @@ def modify(
res = __salt__["cmd.run_all"](
"pdbedit --modify --user {login} {changes}".format(
login=shlex.quote(login), changes=" ".join(cmds),
login=shlex.quote(login),
changes=" ".join(cmds),
),
)

View file

@ -137,7 +137,14 @@ def set_master(
new_conf = []
dict_key = "{} {}".format(service, conn_type)
new_line = _format_master(
service, conn_type, private, unpriv, chroot, wakeup, maxproc, command,
service,
conn_type,
private,
unpriv,
chroot,
wakeup,
maxproc,
command,
)
for line in conf_list:
if isinstance(line, dict):
@ -190,7 +197,14 @@ def _format_master(
maxproc = "-"
conf_line = "{:9s} {:5s} {:7s} {:7s} {:7s} {:7s} {:7s} {}".format(
service, conn_type, private, unpriv, chroot, wakeup, maxproc, command,
service,
conn_type,
private,
unpriv,
chroot,
wakeup,
maxproc,
command,
)
# print(conf_line)
return conf_line

View file

@ -104,7 +104,7 @@ def _get_system():
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
"""
"""
agent = {
"base": USER_AGENT_BASE,
"class": __name__,

View file

@ -92,7 +92,7 @@ def _get_blade():
2) From environment (PUREFB_IP and PUREFB_API)
3) From the pillar (PUREFB_IP and PUREFB_API)
"""
"""
try:
blade_name = __opts__["pure_tags"]["fb"].get("san_ip")

View file

@ -41,7 +41,8 @@ def make_image(location, size, fmt):
if not os.path.isdir(os.path.dirname(location)):
return ""
if not __salt__["cmd.retcode"](
"qemu-img create -f {} {} {}M".format(fmt, location, size), python_shell=False,
"qemu-img create -f {} {} {}M".format(fmt, location, size),
python_shell=False,
):
return location
return ""

View file

@ -198,7 +198,10 @@ def update_item(name, id_, field=None, value=None, postdata=None):
)
status, result = _query(
action=name, command=id_, method="POST", data=salt.utils.json.dumps(postdata),
action=name,
command=id_,
method="POST",
data=salt.utils.json.dumps(postdata),
)
return result

View file

@ -71,8 +71,12 @@ def _parse_image_meta(image=None, detail=False):
if docker_repo and docker_tag:
name = "{}:{}".format(docker_repo, docker_tag)
description = "Docker image imported from {repo}:{tag} on {date}.".format(
repo=docker_repo, tag=docker_tag, date=published,
description = (
"Docker image imported from {repo}:{tag} on {date}.".format(
repo=docker_repo,
tag=docker_tag,
date=published,
)
)
if name and detail:
@ -86,7 +90,9 @@ def _parse_image_meta(image=None, detail=False):
}
elif name:
ret = "{name}@{version} [{published}]".format(
name=name, version=version, published=published,
name=name,
version=version,
published=published,
)
else:
log.debug("smartos_image - encountered invalid image payload: %s", image)

View file

@ -73,7 +73,8 @@ def _get_secret_key(profile):
def _generate_password(email):
m = hmac.new(
base64.b64decode(_get_secret_key("splunk")), str([email, SERVICE_NAME]),
base64.b64decode(_get_secret_key("splunk")),
str([email, SERVICE_NAME]),
)
return base64.urlsafe_b64encode(m.digest()).strip().replace("=", "")

View file

@ -633,7 +633,13 @@ def passwd(passwd, user="", alg="sha1", realm=None):
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update("{}:{}:{}".format(user, realm, passwd,))
digest.update(
"{}:{}:{}".format(
user,
realm,
passwd,
)
)
else:
digest.update(passwd)

View file

@ -63,7 +63,8 @@ def _get_twilio(profile):
"""
creds = __salt__["config.option"](profile)
client = TwilioRestClient(
creds.get("twilio.account_sid"), creds.get("twilio.auth_token"),
creds.get("twilio.account_sid"),
creds.get("twilio.auth_token"),
)
return client

View file

@ -131,7 +131,8 @@ def list_nodes():
"public_ips": [],
}
ret[node]["size"] = "{} RAM, {} CPU".format(
nodes[node]["Memory size"], nodes[node]["Number of CPUs"],
nodes[node]["Memory size"],
nodes[node]["Number of CPUs"],
)
return ret

View file

@ -86,7 +86,8 @@ def healthy():
# if all pools are healthy, otherwise we will get
# the same output that we expect from zpool status
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"]("status", flags=["-x"]), python_shell=False,
__utils__["zfs.zpool_command"]("status", flags=["-x"]),
python_shell=False,
)
return res["stdout"] == "all pools are healthy"
@ -111,7 +112,8 @@ def status(zpool=None):
## collect status output
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"]("status", target=zpool), python_shell=False,
__utils__["zfs.zpool_command"]("status", target=zpool),
python_shell=False,
)
if res["retcode"] != 0:
@ -194,7 +196,10 @@ def status(zpool=None):
# NOTE: transform data into dict
stat_data = OrderedDict(
list(
zip(header, [x for x in line.strip().split(" ") if x not in [""]],)
zip(
header,
[x for x in line.strip().split(" ") if x not in [""]],
)
)
)
@ -307,7 +312,12 @@ def iostat(zpool=None, sample_time=5, parsable=True):
# NOTE: transform data into dict
io_data = OrderedDict(
list(zip(header, [x for x in line.strip().split(" ") if x not in [""]],))
list(
zip(
header,
[x for x in line.strip().split(" ") if x not in [""]],
)
)
)
# NOTE: normalize values
@ -415,7 +425,14 @@ def list_(properties="size,alloc,free,cap,frag,health", zpool=None, parsable=Tru
## parse list output
for line in res["stdout"].splitlines():
# NOTE: transform data into dict
zpool_data = OrderedDict(list(zip(properties, line.strip().split("\t"),)))
zpool_data = OrderedDict(
list(
zip(
properties,
line.strip().split("\t"),
)
)
)
# NOTE: normalize values
if parsable:
@ -547,7 +564,10 @@ def set(zpool, prop, value):
# set property
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](
command="set", property_name=prop, property_value=value, target=zpool,
command="set",
property_name=prop,
property_value=value,
target=zpool,
),
python_shell=False,
)
@ -572,7 +592,10 @@ def exists(zpool):
# list for zpool
# NOTE: retcode > 0 if zpool does not exists
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="list", target=zpool,),
__utils__["zfs.zpool_command"](
command="list",
target=zpool,
),
python_shell=False,
ignore_retcode=True,
)
@ -600,7 +623,9 @@ def destroy(zpool, force=False):
# destroy zpool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](
command="destroy", flags=["-f"] if force else None, target=zpool,
command="destroy",
flags=["-f"] if force else None,
target=zpool,
),
python_shell=False,
)
@ -647,7 +672,11 @@ def scrub(zpool, stop=False, pause=False):
## Scrub storage pool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="scrub", flags=action, target=zpool,),
__utils__["zfs.zpool_command"](
command="scrub",
flags=action,
target=zpool,
),
python_shell=False,
)
@ -827,7 +856,11 @@ def add(zpool, *vdevs, **kwargs):
## Update storage pool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="add", flags=flags, target=target,),
__utils__["zfs.zpool_command"](
command="add",
flags=flags,
target=target,
),
python_shell=False,
)
@ -880,7 +913,11 @@ def attach(zpool, device, new_device, force=False):
## Update storage pool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="attach", flags=flags, target=target,),
__utils__["zfs.zpool_command"](
command="attach",
flags=flags,
target=target,
),
python_shell=False,
)
@ -913,7 +950,10 @@ def detach(zpool, device):
"""
## Update storage pool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="detach", target=[zpool, device],),
__utils__["zfs.zpool_command"](
command="detach",
target=[zpool, device],
),
python_shell=False,
)
@ -1060,7 +1100,11 @@ def replace(zpool, old_device, new_device=None, force=False):
## Replace device
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="replace", flags=flags, target=target,),
__utils__["zfs.zpool_command"](
command="replace",
flags=flags,
target=target,
),
python_shell=False,
)
@ -1100,7 +1144,9 @@ def create_file_vdev(size, *vdevs):
else:
res = __salt__["cmd.run_all"](
"{mkfile} {size} {vdev}".format(
mkfile=_mkfile_cmd, size=size, vdev=vdev,
mkfile=_mkfile_cmd,
size=size,
vdev=vdev,
),
python_shell=False,
)
@ -1150,7 +1196,11 @@ def export(*pools, **kwargs):
## Export pools
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="export", flags=flags, target=targets,),
__utils__["zfs.zpool_command"](
command="export",
flags=flags,
target=targets,
),
python_shell=False,
)
@ -1334,7 +1384,11 @@ def online(zpool, *vdevs, **kwargs):
## Bring online device
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="online", flags=flags, target=target,),
__utils__["zfs.zpool_command"](
command="online",
flags=flags,
target=target,
),
python_shell=False,
)
@ -1384,7 +1438,11 @@ def offline(zpool, *vdevs, **kwargs):
## Take a device offline
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="offline", flags=flags, target=target,),
__utils__["zfs.zpool_command"](
command="offline",
flags=flags,
target=target,
),
python_shell=False,
)
@ -1413,7 +1471,9 @@ def labelclear(device, force=False):
## clear label for all specified device
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](
command="labelclear", flags=["-f"] if force else None, target=device,
command="labelclear",
flags=["-f"] if force else None,
target=device,
),
python_shell=False,
)
@ -1454,7 +1514,10 @@ def clear(zpool, device=None):
## clear storage pool errors
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="clear", target=target,),
__utils__["zfs.zpool_command"](
command="clear",
target=target,
),
python_shell=False,
)
@ -1482,7 +1545,10 @@ def reguid(zpool):
"""
## generate new GUID for pool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="reguid", target=zpool,),
__utils__["zfs.zpool_command"](
command="reguid",
target=zpool,
),
python_shell=False,
)
@ -1507,7 +1573,10 @@ def reopen(zpool):
"""
## reopen all devices fro pool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="reopen", target=zpool,),
__utils__["zfs.zpool_command"](
command="reopen",
target=zpool,
),
python_shell=False,
)
@ -1552,7 +1621,10 @@ def upgrade(zpool=None, version=None):
## Upgrade pool
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](
command="upgrade", flags=flags, opts=opts, target=zpool,
command="upgrade",
flags=flags,
opts=opts,
target=zpool,
),
python_shell=False,
)
@ -1598,7 +1670,11 @@ def history(zpool=None, internal=False, verbose=False):
## Lookup history
res = __salt__["cmd.run_all"](
__utils__["zfs.zpool_command"](command="history", flags=flags, target=zpool,),
__utils__["zfs.zpool_command"](
command="history",
flags=flags,
target=zpool,
),
python_shell=False,
)

View file

@ -93,7 +93,7 @@ class Repo:
"""
def __init__(self, repo_uri):
""" Initialize a hg repo (or open it if it already exists) """
"""Initialize a hg repo (or open it if it already exists)"""
self.repo_uri = repo_uri
cachedir = os.path.join(__opts__["cachedir"], "hg_pillar")
hash_type = getattr(hashlib, __opts__.get("hash_type", "md5"))

View file

@ -133,8 +133,8 @@ class MySQLExtPillar(SqlBaseExtPillar):
def extract_queries(self, args, kwargs): # pylint: disable=useless-super-delegation
"""
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
"""
return super().extract_queries(args, kwargs)

View file

@ -104,8 +104,8 @@ class POSTGRESExtPillar(SqlBaseExtPillar):
def extract_queries(self, args, kwargs): # pylint: disable=useless-super-delegation
"""
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
"""
return super().extract_queries(args, kwargs)

View file

@ -388,9 +388,9 @@ def ext_pillar(minion_id, pillar, **kwargs): # pylint: disable=W0613
] = customValue.value
type_specific_pillar_attribute = []
if type_name in type_specific_pillar_attributes:
type_specific_pillar_attribute = type_specific_pillar_attributes[
type_name
]
type_specific_pillar_attribute = (
type_specific_pillar_attributes[type_name]
)
vmware_pillar[pillar_key] = dictupdate.update(
vmware_pillar[pillar_key],
_crawl_attribute(

View file

@ -60,13 +60,16 @@ def ping():
decode=True,
)
log.debug(
"chronos.info returned successfully: %s", response,
"chronos.info returned successfully: %s",
response,
)
if "dict" in response:
return True
except Exception as ex: # pylint: disable=broad-except
log.error(
"error pinging chronos with base_url %s: %s", CONFIG[CONFIG_BASE_URL], ex,
"error pinging chronos with base_url %s: %s",
CONFIG[CONFIG_BASE_URL],
ex,
)
return False

View file

@ -193,8 +193,10 @@ def get_config_resolver_class(cid=None, hierarchical=False):
if hierarchical is True:
h = "true"
payload = '<configResolveClass cookie="{}" inHierarchical="{}" classId="{}"/>'.format(
cookie, h, cid
payload = (
'<configResolveClass cookie="{}" inHierarchical="{}" classId="{}"/>'.format(
cookie, h, cid
)
)
r = __utils__["http.query"](
DETAILS["url"],

View file

@ -55,10 +55,13 @@ def ping():
"""
try:
response = salt.utils.http.query(
"{}/ping".format(CONFIG[CONFIG_BASE_URL]), decode_type="plain", decode=True,
"{}/ping".format(CONFIG[CONFIG_BASE_URL]),
decode_type="plain",
decode=True,
)
log.debug(
"marathon.info returned successfully: %s", response,
"marathon.info returned successfully: %s",
response,
)
if "text" in response and response["text"].strip() == "pong":
return True

View file

@ -181,7 +181,9 @@ def prep_jid(nocache=False, passed_jid=None):
try:
cb_.add(
str(jid), {"nocache": nocache}, ttl=_get_ttl(),
str(jid),
{"nocache": nocache},
ttl=_get_ttl(),
)
except couchbase.exceptions.KeyExistsError:
# TODO: some sort of sleep or something? Spinning is generally bad practice
@ -202,7 +204,9 @@ def returner(load):
ret_doc = {"return": load["return"], "full_ret": salt.utils.json.dumps(load)}
cb_.add(
hn_key, ret_doc, ttl=_get_ttl(),
hn_key,
ret_doc,
ttl=_get_ttl(),
)
except couchbase.exceptions.KeyExistsError:
log.error(

View file

@ -276,7 +276,8 @@ def returner(ret):
# Prefix the key with the run order so it can be sorted
new_uid = "{}_|-{}".format(
str(data["__run_num__"]).zfill(max_chars), uid,
str(data["__run_num__"]).zfill(max_chars),
uid,
)
ret["return"][new_uid] = ret["return"].pop(uid)

View file

@ -115,7 +115,9 @@ def returner(ret):
client, path = _get_conn(__opts__, write_profile)
# Make a note of this minion for the external job cache
client.set(
"/".join((path, "minions", ret["id"])), ret["jid"], ttl=ttl,
"/".join((path, "minions", ret["id"])),
ret["jid"],
ttl=ttl,
)
for field in ret:
@ -136,7 +138,9 @@ def save_load(jid, load, minions=None):
else:
ttl = __opts__.get("etcd.ttl")
client.set(
"/".join((path, "jobs", jid, ".load.p")), salt.utils.json.dumps(load), ttl=ttl,
"/".join((path, "jobs", jid, ".load.p")),
salt.utils.json.dumps(load),
ttl=ttl,
)

View file

@ -61,8 +61,8 @@ def _get_conn():
def _delivery_report(err, msg):
""" Called once for each message produced to indicate delivery result.
Triggered by poll() or flush(). """
"""Called once for each message produced to indicate delivery result.
Triggered by poll() or flush()."""
if err is not None:
log.error("Message delivery failed: %s", err)
else:

View file

@ -80,7 +80,8 @@ def _send_splunk(event, index_override=None, sourcetype_override=None):
# Get Splunk Options
opts = _get_options()
log.info(
"Options: %s", salt.utils.json.dumps(opts),
"Options: %s",
salt.utils.json.dumps(opts),
)
http_event_collector_key = opts["token"]
http_event_collector_host = opts["indexer"]
@ -107,7 +108,8 @@ def _send_splunk(event, index_override=None, sourcetype_override=None):
# Add the event
payload.update({"event": event})
log.info(
"Payload: %s", salt.utils.json.dumps(payload),
"Payload: %s",
salt.utils.json.dumps(payload),
)
# Fire it off
splunk_event.sendEvent(payload)

View file

@ -388,12 +388,14 @@ def neighbors(*asns, **kwargs):
if "vrf" in display_fields:
row["vrf"] = vrf
if "connection_stats" in display_fields:
connection_stats = "{state} {active}/{received}/{accepted}/{damped}".format(
state=neighbor.get("connection_state", -1),
active=neighbor.get("active_prefix_count", -1),
received=neighbor.get("received_prefix_count", -1),
accepted=neighbor.get("accepted_prefix_count", -1),
damped=neighbor.get("suppressed_prefix_count", -1),
connection_stats = (
"{state} {active}/{received}/{accepted}/{damped}".format(
state=neighbor.get("connection_state", -1),
active=neighbor.get("active_prefix_count", -1),
received=neighbor.get("received_prefix_count", -1),
accepted=neighbor.get("accepted_prefix_count", -1),
damped=neighbor.get("suppressed_prefix_count", -1),
)
)
row["connection_stats"] = connection_stats
if (

View file

@ -540,9 +540,10 @@ def safe_accept(target, tgt_type="glob"):
elif minion not in pending:
failures[minion] = "Minion key {} not found by salt-key".format(minion)
elif pending[minion] != finger:
failures[minion] = (
"Minion key {} does not match the key in "
"salt-key: {}".format(finger, pending[minion])
failures[
minion
] = "Minion key {} does not match the key in " "salt-key: {}".format(
finger, pending[minion]
)
else:
subprocess.call(["salt-key", "-qya", minion])

View file

@ -336,8 +336,10 @@ def interfaces(
net_runner_opts = _get_net_runner_opts()
if pattern:
title = 'Pattern "{}" found in the description of the following interfaces'.format(
pattern
title = (
'Pattern "{}" found in the description of the following interfaces'.format(
pattern
)
)
if not title:
title = "Details"
@ -953,8 +955,10 @@ def find(addr, best=True, display=_DEFAULT_DISPLAY):
elif ip:
device, interface, mac = _find_interfaces_mac(ip)
if device and interface:
title = "IP Address {ip} is set for interface {interface}, on {device}".format(
interface=interface, device=device, ip=ip
title = (
"IP Address {ip} is set for interface {interface}, on {device}".format(
interface=interface, device=device, ip=ip
)
)
results["int_ip"] = interfaces(
device=device, interface=interface, title=title, display=display

View file

@ -167,8 +167,10 @@ def api(server, command, *args, **kwargs):
try:
client, key = _get_session(server)
except Exception as exc: # pylint: disable=broad-except
err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
err_msg = (
"Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
)
)
log.error(err_msg)
return {call: err_msg}
@ -202,8 +204,10 @@ def addGroupsToKey(server, activation_key, groups):
try:
client, key = _get_session(server)
except Exception as exc: # pylint: disable=broad-except
err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
err_msg = (
"Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
)
)
log.error(err_msg)
return {"Error": err_msg}
@ -228,8 +232,10 @@ def deleteAllGroups(server):
try:
client, key = _get_session(server)
except Exception as exc: # pylint: disable=broad-except
err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
err_msg = (
"Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
)
)
log.error(err_msg)
return {"Error": err_msg}
@ -265,8 +271,10 @@ def deleteAllSystems(server):
try:
client, key = _get_session(server)
except Exception as exc: # pylint: disable=broad-except
err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
err_msg = (
"Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
)
)
log.error(err_msg)
return {"Error": err_msg}
@ -299,8 +307,10 @@ def deleteAllActivationKeys(server):
try:
client, key = _get_session(server)
except Exception as exc: # pylint: disable=broad-except
err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
err_msg = (
"Exception raised when connecting to spacewalk server ({}): {}".format(
server, exc
)
)
log.error(err_msg)
return {"Error": err_msg}
@ -336,8 +346,10 @@ def unregister(name, server_url):
try:
client, key = _get_session(server_url)
except Exception as exc: # pylint: disable=broad-except
err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format(
server_url, exc
err_msg = (
"Exception raised when connecting to spacewalk server ({}): {}".format(
server_url, exc
)
)
log.error(err_msg)
return {name: err_msg}

View file

@ -123,7 +123,8 @@ def set_(key, value, profile=None):
conn, cur, table = _connect(profile)
value = memoryview(salt.utils.msgpack.packb(value))
q = profile.get(
"set_query", ("INSERT OR REPLACE INTO {} VALUES (:key, :value)").format(table),
"set_query",
("INSERT OR REPLACE INTO {} VALUES (:key, :value)").format(table),
)
conn.execute(q, {"key": key, "value": value})
conn.commit()

View file

@ -59,7 +59,9 @@ def get(key, service=None, profile=None): # pylint: disable=W0613
request = {"token": profile["token"], "encsecret": key}
result = http.query(
profile["url"], method="POST", data=salt.utils.json.dumps(request),
profile["url"],
method="POST",
data=salt.utils.json.dumps(request),
)
decrypted = result.get("body")

View file

@ -32,7 +32,9 @@ def held(name):
The name of the package, e.g., 'tmux'
"""
ret = {"name": name, "changes": {}, "result": False, "comment": ""}
state = __salt__["pkg.get_selections"](pattern=name,)
state = __salt__["pkg.get_selections"](
pattern=name,
)
if not state:
ret.update(comment="Package {} does not have a state".format(name))
elif not salt.utils.data.is_true(state.get("hold", False)):

View file

@ -1458,9 +1458,10 @@ class _Swagger:
ret = _log_changes(ret, "delete_api", delete_api_response)
else:
ret["comment"] = (
"api already absent for swagger file: "
"{}, desc: {}".format(self.rest_api_name, self.info_json)
ret[
"comment"
] = "api already absent for swagger file: " "{}, desc: {}".format(
self.rest_api_name, self.info_json
)
return ret
@ -1591,13 +1592,12 @@ class _Swagger:
ret["result"] = False
ret["abort"] = True
if "error" in update_model_schema_response:
ret["comment"] = (
"Failed to update existing model {} with schema {}, "
"error: {}".format(
model,
_dict_to_json_pretty(schema),
update_model_schema_response["error"]["message"],
)
ret[
"comment"
] = "Failed to update existing model {} with schema {}, " "error: {}".format(
model,
_dict_to_json_pretty(schema),
update_model_schema_response["error"]["message"],
)
return ret
@ -1616,13 +1616,12 @@ class _Swagger:
ret["result"] = False
ret["abort"] = True
if "error" in create_model_response:
ret["comment"] = (
"Failed to create model {}, schema {}, "
"error: {}".format(
model,
_dict_to_json_pretty(schema),
create_model_response["error"]["message"],
)
ret[
"comment"
] = "Failed to create model {}, schema {}, " "error: {}".format(
model,
_dict_to_json_pretty(schema),
create_model_response["error"]["message"],
)
return ret

View file

@ -61,7 +61,13 @@ def __virtual__():
def present(
name, config, tags, region=None, key=None, keyid=None, profile=None,
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Ensure the CloudFront distribution is present.
@ -108,12 +114,17 @@ def present(
}
res = __salt__["boto_cloudfront.get_distribution"](
name, region=region, key=key, keyid=keyid, profile=profile,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in res:
ret["result"] = False
ret["comment"] = "Error checking distribution {}: {}".format(
name, res["error"],
name,
res["error"],
)
return ret
@ -126,12 +137,19 @@ def present(
return ret
res = __salt__["boto_cloudfront.create_distribution"](
name, config, tags, region=region, key=key, keyid=keyid, profile=profile,
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in res:
ret["result"] = False
ret["comment"] = "Error creating distribution {}: {}".format(
name, res["error"],
name,
res["error"],
)
return ret
@ -149,7 +167,8 @@ def present(
"tags": tags,
}
diffed_config = __utils__["dictdiffer.deep_diff"](
full_config_old, full_config_new,
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
@ -172,7 +191,9 @@ def present(
any_changes = bool("old" in diffed_config or "new" in diffed_config)
if not any_changes:
ret["result"] = True
ret["comment"] = "Distribution {} has correct config.".format(name,)
ret["comment"] = "Distribution {} has correct config.".format(
name,
)
return ret
if __opts__["test"]:
@ -184,12 +205,19 @@ def present(
return ret
res = __salt__["boto_cloudfront.update_distribution"](
name, config, tags, region=region, key=key, keyid=keyid, profile=profile,
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in res:
ret["result"] = False
ret["comment"] = "Error updating distribution {}: {}".format(
name, res["error"],
name,
res["error"],
)
return ret

View file

@ -260,9 +260,10 @@ def pool_present(
if r.get("created"):
updated_identity_pool = r.get("identity_pool")
IdentityPoolId = updated_identity_pool.get("IdentityPoolId")
ret["comment"] = (
"A new identity pool with name {}, id {} "
"is created.".format(IdentityPoolName, IdentityPoolId)
ret[
"comment"
] = "A new identity pool with name {}, id {} " "is created.".format(
IdentityPoolName, IdentityPoolId
)
else:
ret["result"] = False
@ -278,19 +279,19 @@ def pool_present(
if r.get("updated"):
updated_identity_pool = r.get("identity_pool")
ret["comment"] = (
"Existing identity pool with name {}, id {} "
"is updated.".format(IdentityPoolName, IdentityPoolId)
ret[
"comment"
] = "Existing identity pool with name {}, id {} " "is updated.".format(
IdentityPoolName, IdentityPoolId
)
else:
ret["result"] = False
ret["comment"] = (
"Failed to update an existing identity pool {} {}: "
"{}".format(
IdentityPoolName,
IdentityPoolId,
r["error"].get("message", r["error"]),
)
ret[
"comment"
] = "Failed to update an existing identity pool {} {}: " "{}".format(
IdentityPoolName,
IdentityPoolId,
r["error"].get("message", r["error"]),
)
return ret
@ -386,9 +387,10 @@ def pool_absent(
return ret
if __opts__["test"]:
ret["comment"] = (
"The following matched identity pools will be "
"deleted.\n{}".format(identity_pools)
ret[
"comment"
] = "The following matched identity pools will be " "deleted.\n{}".format(
identity_pools
)
ret["result"] = None
return ret
@ -418,8 +420,10 @@ def pool_absent(
)
else:
ret["result"] = False
failure_comment = "Identity Pool Id {} not deleted, returned count 0".format(
IdentityPoolId
failure_comment = (
"Identity Pool Id {} not deleted, returned count 0".format(
IdentityPoolId
)
)
ret["comment"] = "{}\n{}".format(ret["comment"], failure_comment)
return ret

View file

@ -142,7 +142,12 @@ def present(
return ret
result_create_pipeline = __salt__["boto_datapipeline.create_pipeline"](
name, name, region=region, key=key, keyid=keyid, profile=profile,
name,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in result_create_pipeline:
ret["result"] = False
@ -171,7 +176,11 @@ def present(
if _immutable_fields_error(result_pipeline_definition):
# If update not possible, delete and retry
result_delete_pipeline = __salt__["boto_datapipeline.delete_pipeline"](
pipeline_id, region=region, key=key, keyid=keyid, profile=profile,
pipeline_id,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in result_delete_pipeline:
ret["result"] = False
@ -181,7 +190,12 @@ def present(
return ret
result_create_pipeline = __salt__["boto_datapipeline.create_pipeline"](
name, name, region=region, key=key, keyid=keyid, profile=profile,
name,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in result_create_pipeline:
ret["result"] = False
@ -218,7 +232,11 @@ def present(
return ret
result_activate_pipeline = __salt__["boto_datapipeline.activate_pipeline"](
pipeline_id, region=region, key=key, keyid=keyid, profile=profile,
pipeline_id,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in result_activate_pipeline:
ret["result"] = False
@ -303,7 +321,11 @@ def _pipeline_present_with_definition(
that contains a dict with region, key and keyid.
"""
result_pipeline_id = __salt__["boto_datapipeline.pipeline_id_from_name"](
name, region=region, key=key, keyid=keyid, profile=profile,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in result_pipeline_id:
return False, {}
@ -565,7 +587,11 @@ def absent(name, region=None, key=None, keyid=None, profile=None):
ret = {"name": name, "result": True, "comment": "", "changes": {}}
result_pipeline_id = __salt__["boto_datapipeline.pipeline_id_from_name"](
name, region=region, key=key, keyid=keyid, profile=profile,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" not in result_pipeline_id:
pipeline_id = result_pipeline_id["result"]
@ -575,7 +601,11 @@ def absent(name, region=None, key=None, keyid=None, profile=None):
return ret
else:
__salt__["boto_datapipeline.delete_pipeline"](
pipeline_id, region=region, key=key, keyid=keyid, profile=profile,
pipeline_id,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
ret["changes"]["old"] = {"pipeline_id": pipeline_id}
ret["changes"]["new"] = None

View file

@ -632,7 +632,12 @@ def _update_global_secondary_indexes(
changes_old.setdefault("global_indexes", {})
changes_new.setdefault("global_indexes", {})
success = __salt__["boto_dynamodb.update_global_secondary_index"](
name, index_updates, region=region, key=key, keyid=keyid, profile=profile,
name,
index_updates,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if success:

View file

@ -1001,11 +1001,10 @@ def instance_present(
if r[0].get("instance_id"):
if r[0]["instance_id"] != instance_id:
ret["result"] = False
ret["comment"] = (
"EIP {} is already associated with instance "
"{}.".format(
public_ip if public_ip else allocation_id, r[0]["instance_id"]
)
ret[
"comment"
] = "EIP {} is already associated with instance " "{}.".format(
public_ip if public_ip else allocation_id, r[0]["instance_id"]
)
return ret
else:
@ -1228,9 +1227,10 @@ def instance_absent(
)
except CommandExecutionError as e:
ret["result"] = None
ret["comment"] = (
"Couldn't determine current status of instance "
"{}.".format(instance_name or name)
ret[
"comment"
] = "Couldn't determine current status of instance " "{}.".format(
instance_name or name
)
return ret
@ -1434,8 +1434,10 @@ def volume_absent(
ret["comment"] = "Volume matching criteria not found, assuming already absent"
return ret
if len(vols) > 1:
msg = "More than one volume matched criteria, can't continue in state {}".format(
name
msg = (
"More than one volume matched criteria, can't continue in state {}".format(
name
)
)
log.error(msg)
ret["comment"] = msg
@ -2075,12 +2077,11 @@ def private_ips_absent(
else:
# Testing mode, show that there were ips to remove
ret["comment"] = (
"ips on eni: {}\n"
"ips that would be removed: {}\n".format(
"\n\t- " + "\n\t- ".join(ret["changes"]["old"]),
"\n\t- " + "\n\t- ".join(ips_to_remove),
)
ret[
"comment"
] = "ips on eni: {}\n" "ips that would be removed: {}\n".format(
"\n\t- " + "\n\t- ".join(ret["changes"]["old"]),
"\n\t- " + "\n\t- ".join(ips_to_remove),
)
ret["changes"] = {}
ret["result"] = None

View file

@ -275,11 +275,11 @@ def present(
)["domain"]
if _status.get("ElasticsearchVersion") != str(ElasticsearchVersion):
ret["result"] = False
ret["comment"] = (
"Failed to update domain: version cannot be modified "
"from {} to {}.".format(
_status.get("ElasticsearchVersion"), str(ElasticsearchVersion),
)
ret[
"comment"
] = "Failed to update domain: version cannot be modified " "from {} to {}.".format(
_status.get("ElasticsearchVersion"),
str(ElasticsearchVersion),
)
return ret
_describe = __salt__["boto_elasticsearch_domain.describe"](

View file

@ -470,9 +470,10 @@ def replica_present(
)
if not modified:
ret["result"] = False
ret["comment"] = (
"Failed to update parameter group of {} RDS "
"instance.".format(name)
ret[
"comment"
] = "Failed to update parameter group of {} RDS " "instance.".format(
name
)
ret["changes"]["old"] = pmg_name
ret["changes"]["new"] = db_parameter_group_name

View file

@ -187,12 +187,18 @@ def object_present(
digest = salt.utils.hashutils.get_hash(source, form=hash_type)
except OSError as e:
ret["result"] = False
ret["comment"] = "Could not read local file {}: {}".format(source, e,)
ret["comment"] = "Could not read local file {}: {}".format(
source,
e,
)
return ret
except ValueError as e:
# Invalid hash type exception from get_hash
ret["result"] = False
ret["comment"] = "Could not hash local file {}: {}".format(source, e,)
ret["comment"] = "Could not hash local file {}: {}".format(
source,
e,
)
return ret
HASH_METADATA_KEY = "salt_managed_content_hash"
@ -227,7 +233,9 @@ def object_present(
)
if "error" in r:
ret["result"] = False
ret["comment"] = "Failed to check if S3 object exists: {}.".format(r["error"],)
ret["comment"] = "Failed to check if S3 object exists: {}.".format(
r["error"],
)
return ret
if r["result"]:
@ -284,7 +292,10 @@ def object_present(
if "error" in r:
ret["result"] = False
ret["comment"] = "Failed to {} S3 object: {}.".format(action, r["error"],)
ret["comment"] = "Failed to {} S3 object: {}.".format(
action,
r["error"],
)
return ret
ret["result"] = True

View file

@ -75,7 +75,12 @@ def __virtual__():
def present(
name, attributes=None, region=None, key=None, keyid=None, profile=None,
name,
attributes=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Ensure the SQS queue exists.
@ -107,7 +112,11 @@ def present(
}
r = __salt__["boto_sqs.exists"](
name, region=region, key=key, keyid=keyid, profile=profile,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in r:
ret["result"] = False
@ -119,7 +128,9 @@ def present(
else:
if __opts__["test"]:
ret["result"] = None
ret["comment"].append("SQS queue {} is set to be created.".format(name),)
ret["comment"].append(
"SQS queue {} is set to be created.".format(name),
)
ret["changes"] = {"old": None, "new": name}
return ret
@ -148,11 +159,17 @@ def present(
return ret
r = __salt__["boto_sqs.get_attributes"](
name, region=region, key=key, keyid=keyid, profile=profile,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in r:
ret["result"] = False
ret["comment"].append("Failed to get queue attributes: {}".format(r["error"]),)
ret["comment"].append(
"Failed to get queue attributes: {}".format(r["error"]),
)
return ret
current_attributes = r["result"]
@ -198,27 +215,41 @@ def present(
ret["result"] = None
ret["comment"].append(
"Attribute(s) {} set to be updated:\n{}".format(
attr_names, attributes_diff,
attr_names,
attributes_diff,
)
)
ret["changes"] = {"attributes": {"diff": attributes_diff}}
return ret
r = __salt__["boto_sqs.set_attributes"](
name, attrs_to_set, region=region, key=key, keyid=keyid, profile=profile,
name,
attrs_to_set,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in r:
ret["result"] = False
ret["comment"].append("Failed to set queue attributes: {}".format(r["error"]),)
ret["comment"].append(
"Failed to set queue attributes: {}".format(r["error"]),
)
return ret
ret["comment"].append("Updated SQS queue attribute(s) {}.".format(attr_names),)
ret["comment"].append(
"Updated SQS queue attribute(s) {}.".format(attr_names),
)
ret["changes"]["attributes"] = {"diff": attributes_diff}
return ret
def absent(
name, region=None, key=None, keyid=None, profile=None,
name,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Ensure the named sqs queue is deleted.
@ -242,7 +273,11 @@ def absent(
ret = {"name": name, "result": True, "comment": "", "changes": {}}
r = __salt__["boto_sqs.exists"](
name, region=region, key=key, keyid=keyid, profile=profile,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in r:
ret["result"] = False
@ -250,7 +285,10 @@ def absent(
return ret
if not r["result"]:
ret["comment"] = "SQS queue {} does not exist in {}.".format(name, region,)
ret["comment"] = "SQS queue {} does not exist in {}.".format(
name,
region,
)
return ret
if __opts__["test"]:
@ -260,7 +298,11 @@ def absent(
return ret
r = __salt__["boto_sqs.delete"](
name, region=region, key=key, keyid=keyid, profile=profile,
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if "error" in r:
ret["result"] = False

View file

@ -1262,8 +1262,10 @@ def _routes_present(
profile=profile,
)
if "error" in r:
msg = "Error looking up id for VPC peering connection {}: {}".format(
i.get("vpc_peering_connection_name"), r["error"]["message"]
msg = (
"Error looking up id for VPC peering connection {}: {}".format(
i.get("vpc_peering_connection_name"), r["error"]["message"]
)
)
ret["comment"] = msg
ret["result"] = False
@ -1478,8 +1480,10 @@ def _subnets_present(
profile=profile,
)
if "error" in r:
msg = "Failed to associate subnet {} with route table {}: {}.".format(
sn, route_table_name, r["error"]["message"]
msg = (
"Failed to associate subnet {} with route table {}: {}.".format(
sn, route_table_name, r["error"]["message"]
)
)
ret["comment"] = msg
ret["result"] = False
@ -2035,11 +2039,10 @@ def vpc_peering_connection_present(
keyid=keyid,
profile=profile,
):
ret["comment"] = (
"VPC peering {} already requested - pending "
"acceptance by {}".format(
conn_name, peer_owner_id or peer_vpc_name or peer_vpc_id
)
ret[
"comment"
] = "VPC peering {} already requested - pending " "acceptance by {}".format(
conn_name, peer_owner_id or peer_vpc_name or peer_vpc_id
)
log.info(ret["comment"])
return ret

View file

@ -48,7 +48,9 @@ def config(name, config):
if existing_config:
update_config = copy.deepcopy(existing_config)
salt.utils.configcomparer.compare_and_update_config(
config, update_config, ret["changes"],
config,
update_config,
ret["changes"],
)
else:
# the job is not configured--we need to create it from scratch
@ -76,10 +78,12 @@ def config(name, config):
log.debug("_old schedule: %s", _old)
if len(_new) == 3 and len(_old) == 3:
log.debug(
"_new[0] == _old[0]: %s", str(_new[0]) == str(_old[0]),
"_new[0] == _old[0]: %s",
str(_new[0]) == str(_old[0]),
)
log.debug(
"_new[2] == _old[2]: %s", str(_new[2]) == str(_old[2]),
"_new[2] == _old[2]: %s",
str(_new[2]) == str(_old[2]),
)
if str(_new[0]) == str(_old[0]) and str(_new[2]) == str(
_old[2]
@ -100,7 +104,8 @@ def config(name, config):
if "exception" in update_result:
ret["result"] = False
ret["comment"] = "Failed to update job config for {}: {}".format(
name, update_result["exception"],
name,
update_result["exception"],
)
return ret
else:

View file

@ -188,7 +188,8 @@ def _resolve_image(ret, image, client_timeout):
# Image not pulled locally, so try pulling it
try:
pull_result = __salt__["docker.pull"](
image, client_timeout=client_timeout,
image,
client_timeout=client_timeout,
)
except Exception as exc: # pylint: disable=broad-except
raise CommandExecutionError("Failed to pull {}: {}".format(image, exc))
@ -1843,7 +1844,9 @@ def running(
if not skip_comparison:
container_changes = __salt__["docker.compare_containers"](
name, temp_container_name, ignore="Hostname",
name,
temp_container_name,
ignore="Hostname",
)
if container_changes:
if _check_diff(container_changes):
@ -2273,9 +2276,10 @@ def run(
pass
else:
ret["result"] = False if failhard and retcode != 0 else True
ret["comment"] = (
"Container ran and exited with a return code of "
"{}".format(retcode)
ret[
"comment"
] = "Container ran and exited with a return code of " "{}".format(
retcode
)
if remove:

View file

@ -619,9 +619,10 @@ def present(
# Set the comment now to say that it already exists, if we need to
# recreate the network with new config we'll update the comment later.
ret["comment"] = (
"Network '{}' already exists, and is configured "
"as specified".format(name)
ret[
"comment"
] = "Network '{}' already exists, and is configured " "as specified".format(
name
)
log.trace("Details of docker network '%s': %s", name, network)

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