Update bare exceptions to specify Exception.

This will keep us from accidentally catching program-exiting exceptions
like KeyboardInterupt and SystemExit.
This commit is contained in:
Toshio Kuratomi
2018-09-07 17:59:46 -07:00
parent 5147e792d3
commit 3fba006207
320 changed files with 659 additions and 656 deletions

View File

@@ -153,7 +153,7 @@ from ansible.module_utils.aws.direct_connect import (DirectConnectError, delete_
try:
from botocore.exceptions import BotoCoreError, ClientError
except:
except Exception:
pass
# handled by imported AnsibleAWSModule

View File

@@ -162,7 +162,7 @@ import time
try:
import botocore
except:
except Exception:
pass
# handled by imported HAS_BOTO3

View File

@@ -201,7 +201,7 @@ def do_grant(kms, keyarn, role_arn, granttypes, mode='grant', dry_run=True, clea
kms.put_key_policy(KeyId=keyarn, PolicyName='default', Policy=policy_json_string)
# returns nothing, so we have to just assume it didn't throw
ret['changed'] = True
except:
except Exception:
raise
ret['changes_needed'] = changes_needed

View File

@@ -91,7 +91,7 @@ rules:
try:
from botocore.exceptions import ClientError, BotoCoreError
except:
except Exception:
# handled by HAS_BOTO3 check in main
pass

View File

@@ -166,7 +166,7 @@ def create_update_parameter(client, module):
try:
existing_parameter = client.get_parameter(Name=args['Name'], WithDecryption=True)
except:
except Exception:
pass
if existing_parameter:

View File

@@ -477,7 +477,7 @@ def stack_operation(cfn, stack_name, operation, events_limit, op_token=None):
try:
stack = get_stack_facts(cfn, stack_name)
existed.append('yes')
except:
except Exception:
# If the stack previously existed, and now can't be found then it's
# been deleted successfully.
if 'yes' in existed or operation == 'DELETE': # stacks may delete fast, look in a few ways.

View File

@@ -608,7 +608,7 @@ def get_reservations(module, ec2, vpc, tags=None, state=None, zone=None):
if isinstance(tags, str):
try:
tags = literal_eval(tags)
except:
except Exception:
pass
# if not a string type, convert and make sure it's a text string

View File

@@ -1156,7 +1156,7 @@ def create_autoscaling_group(connection):
else:
try:
ag['LaunchConfigurationName'] = as_group['LaunchConfigurationName']
except:
except Exception:
launch_template = as_group['LaunchTemplate']
# Prefer LaunchTemplateId over Name as it's more specific. Only one can be used for update_asg.
ag['LaunchTemplate'] = {"LaunchTemplateId": launch_template['LaunchTemplateId'], "Version": launch_template['Version']}

View File

@@ -516,7 +516,7 @@ class ElbManager(object):
def get_info(self):
try:
check_elb = self.elb_conn.get_all_load_balancers(self.name)[0]
except:
except Exception:
check_elb = None
if not check_elb:
@@ -528,11 +528,11 @@ class ElbManager(object):
else:
try:
lb_cookie_policy = check_elb.policies.lb_cookie_stickiness_policies[0].__dict__['policy_name']
except:
except Exception:
lb_cookie_policy = None
try:
app_cookie_policy = check_elb.policies.app_cookie_stickiness_policies[0].__dict__['policy_name']
except:
except Exception:
app_cookie_policy = None
info = {

View File

@@ -506,7 +506,7 @@ class Ec2Metadata(object):
self._data['%s' % (new_uri)] = content
for (key, value) in dict.items():
self._data['%s:%s' % (new_uri, key.lower())] = value
except:
except Exception:
self._data['%s' % (new_uri)] = content # not a stringifed JSON string
def fix_invalid_varnames(self, data):

View File

@@ -124,7 +124,7 @@ from ansible.module_utils.ec2 import boto3_tag_list_to_ansible_dict, ansible_dic
try:
from botocore.exceptions import BotoCoreError, ClientError
except:
except Exception:
pass # Handled by AnsibleAWSModule

View File

@@ -306,7 +306,7 @@ def run(ecr, params, verbosity):
ecr.set_repository_policy(
registry_id, name, policy_text, force_set_policy)
result['changed'] = True
except:
except Exception:
# Some failure w/ the policy. It's helpful to know what the
# policy is.
result['policy'] = policy_text

View File

@@ -512,7 +512,7 @@ class ElbManager(object):
def get_info(self):
try:
check_elb = self.elb_conn.get_all_load_balancers(self.name)[0]
except:
except Exception:
check_elb = None
if not check_elb:
@@ -524,11 +524,11 @@ class ElbManager(object):
else:
try:
lb_cookie_policy = check_elb.policies.lb_cookie_stickiness_policies[0].__dict__['policy_name']
except:
except Exception:
lb_cookie_policy = None
try:
app_cookie_policy = check_elb.policies.app_cookie_stickiness_policies[0].__dict__['policy_name']
except:
except Exception:
app_cookie_policy = None
info = {

View File

@@ -134,7 +134,7 @@ from ansible.module_utils.ec2 import get_aws_connection_info, boto3_conn
try:
from botocore.exceptions import ClientError
except:
except Exception:
pass # will be protected by AnsibleAWSModule

View File

@@ -224,7 +224,7 @@ def set_queue_attribute(queue, attribute, value, check_mode=False):
try:
existing_value = queue.get_attributes(attributes=attribute)[attribute]
except:
except Exception:
existing_value = ''
# convert dict attributes to JSON strings (sort keys for comparing)

View File

@@ -68,7 +68,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureHttpError
except:
except Exception:
# handled in azure_rm_common
pass

View File

@@ -121,7 +121,7 @@ appserviceplans:
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -74,7 +74,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# handled in azure_rm_common
pass

View File

@@ -120,7 +120,7 @@ try:
from azure.mgmt.cdn.models import ErrorResponseException
from azure.common import AzureHttpError
from azure.mgmt.cdn import CdnManagementClient
except:
except Exception:
# handled in azure_rm_common
pass

View File

@@ -590,7 +590,7 @@ class AzureRMDeploymentManager(AzureRMModuleBase):
)
for op in self._get_failed_nested_operations(operations)
]
except:
except Exception:
# If we fail here, the original error gets lost and user receives wrong error message/stacktrace
pass
self.log(dict(failed_deployment_operations=results), pretty_print=True)

View File

@@ -98,7 +98,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -80,7 +80,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -100,7 +100,7 @@ azure_functionapps:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -167,7 +167,7 @@ images:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -86,7 +86,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureHttpError
except:
except Exception:
# handled in azure_rm_common
pass

View File

@@ -79,7 +79,7 @@ from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# handled in azure_rm_common
pass

View File

@@ -108,7 +108,7 @@ azure_networkinterfaces:
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except:
except Exception:
# This is handled in azure_rm_common
pass
@@ -165,7 +165,7 @@ class AzureRMNetworkInterfaceFacts(AzureRMModuleBase):
item = None
try:
item = self.network_client.network_interfaces.get(self.resource_group, self.name)
except:
except Exception:
pass
if item and self.has_tags(item.tags, self.tags):

View File

@@ -77,7 +77,7 @@ azure_publicipaddresses:
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -258,7 +258,7 @@ class AzureRMResource(AzureRMModuleBase):
try:
response = json.loads(original.text)
needs_update = (dict_merge(response, self.body) != response)
except:
except Exception:
pass
if needs_update:
@@ -266,7 +266,7 @@ class AzureRMResource(AzureRMModuleBase):
if self.state == 'present':
try:
response = json.loads(response.text)
except:
except Exception:
response = response.text
else:
response = None

View File

@@ -198,7 +198,7 @@ class AzureRMResourceFacts(AzureRMModuleBase):
self.results['response'] = response
else:
self.results['response'] = [response]
except:
except Exception:
self.results['response'] = []
return self.results

View File

@@ -77,7 +77,7 @@ azure_resourcegroups:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -98,7 +98,7 @@ routes:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -190,7 +190,7 @@ azure_securitygroups:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -93,7 +93,7 @@ azure_storageaccounts:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -141,7 +141,7 @@ from ansible.module_utils.common.dict_transformations import (
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureHttpError
except:
except Exception:
# handled in azure_rm_common
pass

View File

@@ -210,7 +210,7 @@ from ansible.module_utils.common.dict_transformations import _camel_to_snake
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureHttpError
except:
except Exception:
# handled in azure_rm_common
pass

View File

@@ -190,7 +190,7 @@ vms:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -240,7 +240,7 @@ import re
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# handled in azure_rm_common
pass
@@ -308,7 +308,7 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase):
subnet_id = (vmss['properties']['virtualMachineProfile']['networkProfile']['networkInterfaceConfigurations'][0]
['properties']['ipConfigurations'][0]['properties']['subnet']['id'])
subnet_name = re.sub('.*subnets\\/', '', subnet_id)
except:
except Exception:
self.log('Could not extract subnet name')
try:
@@ -316,13 +316,13 @@ class AzureRMVirtualMachineScaleSetFacts(AzureRMModuleBase):
['properties']['ipConfigurations'][0]['properties']['loadBalancerBackendAddressPools'][0]['id'])
load_balancer_name = re.sub('\\/backendAddressPools.*', '', re.sub('.*loadBalancers\\/', '', backend_address_pool_id))
virtual_network_name = re.sub('.*virtualNetworks\\/', '', re.sub('\\/subnets.*', '', subnet_id))
except:
except Exception:
self.log('Could not extract load balancer / virtual network name')
try:
ssh_password_enabled = (not vmss['properties']['virtualMachineProfile']['osProfile'],
['linuxConfiguration']['disablePasswordAuthentication'])
except:
except Exception:
self.log('Could not extract SSH password enabled')
data_disks = vmss['properties']['virtualMachineProfile']['storageProfile'].get('dataDisks', [])

View File

@@ -90,7 +90,7 @@ azure_vmimages:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -86,7 +86,7 @@ azure_virtualnetworks:
try:
from msrestazure.azure_exceptions import CloudError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -150,7 +150,7 @@ try:
from msrestazure.azure_exceptions import CloudError
from msrestazure.azure_operation import AzureOperationPoller
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except:
except Exception:
# This is handled in azure_rm_common
pass

View File

@@ -165,7 +165,7 @@ class CloudStackFacts(object):
try:
# this data come form users, we try what we can to parse it...
return yaml.safe_load(self._fetch(CS_USERDATA_BASE_URL))
except:
except Exception:
return None
def _fetch(self, path):

View File

@@ -890,7 +890,7 @@ try:
else:
from docker.utils.types import Ulimit, LogConfig
from docker.errors import APIError, NotFound
except Exception as dummy:
except Exception:
# missing docker-py handled in ansible.module_utils.docker
pass

View File

@@ -263,7 +263,7 @@ try:
from docker.errors import NotFound
if LooseVersion(docker_version) >= LooseVersion('2.0.0'):
from docker.types import IPAMPool, IPAMConfig
except Exception as dummy:
except Exception:
# missing docker-py handled in ansible.module_utils.docker_common
pass

View File

@@ -471,7 +471,7 @@ from ansible.module_utils._text import to_text
try:
from distutils.version import LooseVersion
from docker import types
except Exception as dummy:
except Exception:
# missing docker-py handled in ansible.module_utils.docker
pass
@@ -846,7 +846,7 @@ class DockerService(DockerBaseClass):
network_id = None
try:
network_id = list(filter(lambda n: n['name'] == network_name, docker_networks))[0]['id']
except Exception as dummy:
except Exception:
pass
if network_id:
networks.append({'Target': network_id})

View File

@@ -330,11 +330,11 @@ def get_instance_info(inst):
try:
netname = inst.extra['networkInterfaces'][0]['network'].split('/')[-1]
except:
except Exception:
netname = None
try:
subnetname = inst.extra['networkInterfaces'][0]['subnetwork'].split('/')[-1]
except:
except Exception:
subnetname = None
if 'disks' in inst.extra:
disk_names = [disk_info['source'].split('/')[-1]

View File

@@ -239,7 +239,7 @@ def main():
zone, node_name = node.split('/')
nodes.append(gce.ex_get_node(node_name, zone))
output_nodes.append(node)
except:
except Exception:
# skip nodes that are badly formatted or don't exist
pass
try:

View File

@@ -188,7 +188,7 @@ def main():
is_attached = True
json_output['attached_mode'] = d['mode']
json_output['attached_to_instance'] = inst.name
except:
except Exception:
pass
# find disk if it already exists
@@ -210,7 +210,7 @@ def main():
size_gb = int(round(float(size_gb)))
if size_gb < 1:
raise Exception
except:
except Exception:
module.fail_json(msg="Must supply a size_gb larger than 1 GB",
changed=False)

View File

@@ -203,7 +203,7 @@ def _validate_params(params):
try:
check_params(params, fields)
_validate_backend_params(params['backends'])
except:
except Exception:
raise
return (True, '')
@@ -233,7 +233,7 @@ def _validate_backend_params(backends):
for backend in backends:
try:
check_params(backend, fields)
except:
except Exception:
raise
if 'max_rate' in backend and 'max_rate_per_instance' in backend:

View File

@@ -178,7 +178,7 @@ def get_global_forwarding_rule(client, name, project_id=None):
req = client.globalForwardingRules().get(
project=project_id, forwardingRule=name)
return GCPUtils.execute_api_client_req(req, raise_404=False)
except:
except Exception:
raise
@@ -204,7 +204,7 @@ def create_global_forwarding_rule(client, params, project_id):
name=params['forwarding_rule_name'],
project_id=project_id)
return (True, return_data)
except:
except Exception:
raise
@@ -229,7 +229,7 @@ def delete_global_forwarding_rule(client, name, project_id):
project=project_id, forwardingRule=name)
return_data = GCPUtils.execute_api_client_req(req, client)
return (True, return_data)
except:
except Exception:
raise
@@ -270,7 +270,7 @@ def update_global_forwarding_rule(client, forwarding_rule, params, name, project
return_data = GCPUtils.execute_api_client_req(
req, client=client, raw=False)
return (True, return_data)
except:
except Exception:
raise

View File

@@ -261,7 +261,7 @@ def get_healthcheck(client, name, project_id=None, resource_type='HTTP'):
args = {'project': project_id, entity_name: name}
req = resource.get(**args)
return GCPUtils.execute_api_client_req(req, raise_404=False)
except:
except Exception:
raise
@@ -289,7 +289,7 @@ def create_healthcheck(client, params, project_id, resource_type='HTTP'):
name=params['healthcheck_name'],
project_id=project_id)
return (True, return_data)
except:
except Exception:
raise
@@ -315,7 +315,7 @@ def delete_healthcheck(client, name, project_id, resource_type='HTTP'):
req = resource.delete(**args)
return_data = GCPUtils.execute_api_client_req(req, client)
return (True, return_data)
except:
except Exception:
raise
@@ -356,7 +356,7 @@ def update_healthcheck(client, healthcheck, params, name, project_id,
return_data = GCPUtils.execute_api_client_req(
req, client=client, raw=False)
return (True, return_data)
except:
except Exception:
raise

View File

@@ -161,7 +161,7 @@ def create_target_http_proxy(client, params, project_id):
name=params['target_proxy_name'],
project_id=project_id)
return (True, return_data)
except:
except Exception:
raise
@@ -186,7 +186,7 @@ def delete_target_http_proxy(client, name, project_id):
project=project_id, targetHttpProxy=name)
return_data = GCPUtils.execute_api_client_req(req, client)
return (True, return_data)
except:
except Exception:
raise
@@ -227,7 +227,7 @@ def update_target_http_proxy(client, target_proxy, params, name, project_id):
return_data = GCPUtils.execute_api_client_req(
req, client=client, raw=False)
return (True, return_data)
except:
except Exception:
raise

View File

@@ -178,7 +178,7 @@ def _validate_params(params):
_validate_path_matcher_params(params['path_matchers'])
if 'host_rules' in params and params['host_rules'] is not None:
_validate_host_rules_params(params['host_rules'])
except:
except Exception:
raise
return (True, '')
@@ -220,7 +220,7 @@ def _validate_path_matcher_params(path_matchers):
if not path.startswith('/'):
raise ValueError("path for %s must start with /" % (
pm['name']))
except:
except Exception:
raise
return (True, '')
@@ -259,7 +259,7 @@ def _validate_host_rules_params(host_rules):
raise ValueError("wildcard be followed by a '.' or '-', %s" % (
host))
except:
except Exception:
raise
return (True, '')
@@ -341,7 +341,7 @@ def get_url_map(client, name, project_id=None):
try:
req = client.urlMaps().get(project=project_id, urlMap=name)
return GCPUtils.execute_api_client_req(req, raise_404=False)
except:
except Exception:
raise
@@ -367,7 +367,7 @@ def create_url_map(client, params, project_id):
name=params['url_map_name'],
project_id=project_id)
return (True, return_data)
except:
except Exception:
raise
@@ -391,7 +391,7 @@ def delete_url_map(client, name, project_id):
req = client.urlMaps().delete(project=project_id, urlMap=name)
return_data = GCPUtils.execute_api_client_req(req, client)
return (True, return_data)
except:
except Exception:
raise
@@ -431,7 +431,7 @@ def update_url_map(client, url_map, params, name, project_id):
urlMap=name, body=gcp_dict)
return_data = GCPUtils.execute_api_client_req(req, client=client, raw=False)
return (True, return_data)
except:
except Exception:
raise

View File

@@ -228,7 +228,7 @@ def conn(url, user, password):
api = API(url=url, username=user, password=password, insecure=True)
try:
value = api.test()
except:
except Exception:
raise Exception("error connecting to the oVirt API")
return api
@@ -262,16 +262,16 @@ def create_vm(conn, vmtype, vmname, zone, vmdisk_size, vmcpus, vmnic, vmnetwork,
try:
conn.vms.add(vmparams)
except:
except Exception:
raise Exception("Error creating VM with specified parameters")
vm = conn.vms.get(name=vmname)
try:
vm.disks.add(vmdisk)
except:
except Exception:
raise Exception("Error attaching disk")
try:
vm.nics.add(nic_net1)
except:
except Exception:
raise Exception("Error adding nic")
@@ -280,7 +280,7 @@ def create_vm_template(conn, vmname, image, zone):
vmparams = params.VM(name=vmname, cluster=conn.clusters.get(name=zone), template=conn.templates.get(name=image), disks=params.Disks(clone=True))
try:
conn.vms.add(vmparams)
except:
except Exception:
raise Exception('error adding template %s' % image)

View File

@@ -339,7 +339,7 @@ class RHEVConn(object):
api = API(url=url, username=user, password=password, insecure=str(insecure_api))
api.test()
self.conn = api
except:
except Exception:
raise Exception("Failed to connect to RHEV-M.")
def __del__(self):

View File

@@ -354,7 +354,7 @@ class Virt(object):
results.append(x.name())
else:
results.append(x.name())
except:
except Exception:
pass
return results

View File

@@ -229,7 +229,7 @@ class LibvirtConnection(object):
else:
try:
state = self.find_entry(entryid).isActive()
except:
except Exception:
return self.module.exit_json(changed=True)
if not state:
return self.module.exit_json(changed=True)
@@ -302,7 +302,7 @@ class LibvirtConnection(object):
try:
state = self.find_entry(entryid).isActive()
return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
except:
except Exception:
return ENTRY_STATE_ACTIVE_MAP.get("inactive", "unknown")
def get_uuid(self, entryid):
@@ -315,7 +315,7 @@ class LibvirtConnection(object):
xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
try:
result = xml.xpath('/network/forward')[0].get('mode')
except:
except Exception:
raise ValueError('Forward mode not specified')
return result
@@ -323,7 +323,7 @@ class LibvirtConnection(object):
xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
try:
result = xml.xpath('/network/domain')[0].get('name')
except:
except Exception:
raise ValueError('Domain not specified')
return result
@@ -331,7 +331,7 @@ class LibvirtConnection(object):
xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
try:
result = xml.xpath('/network/mac')[0].get('address')
except:
except Exception:
raise ValueError('MAC address not specified')
return result
@@ -345,7 +345,7 @@ class LibvirtConnection(object):
else:
try:
return self.find_entry(entryid).autostart()
except:
except Exception:
return self.module.exit_json(changed=True)
def set_autostart(self, entryid, val):
@@ -354,7 +354,7 @@ class LibvirtConnection(object):
else:
try:
state = self.find_entry(entryid).autostart()
except:
except Exception:
return self.module.exit_json(changed=True)
if bool(state) != val:
return self.module.exit_json(changed=True)
@@ -376,7 +376,7 @@ class LibvirtConnection(object):
else:
try:
self.find_entry(entryid)
except:
except Exception:
return self.module.exit_json(changed=True)

View File

@@ -262,7 +262,7 @@ class LibvirtConnection(object):
else:
try:
state = self.find_entry(entryid).isActive()
except:
except Exception:
return self.module.exit_json(changed=True)
if not state:
return self.module.exit_json(changed=True)
@@ -293,7 +293,7 @@ class LibvirtConnection(object):
try:
state = self.find_entry(entryid).isActive()
return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
except:
except Exception:
return ENTRY_STATE_ACTIVE_MAP.get("inactive", "unknown")
def get_uuid(self, entryid):
@@ -319,14 +319,14 @@ class LibvirtConnection(object):
result.append(device.get('path'))
try:
return result
except:
except Exception:
raise ValueError('No devices specified')
def get_format(self, entryid):
xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
try:
result = xml.xpath('/pool/source/format')[0].get('type')
except:
except Exception:
raise ValueError('Format not specified')
return result
@@ -334,7 +334,7 @@ class LibvirtConnection(object):
xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
try:
result = xml.xpath('/pool/source/host')[0].get('name')
except:
except Exception:
raise ValueError('Host not specified')
return result
@@ -342,7 +342,7 @@ class LibvirtConnection(object):
xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
try:
result = xml.xpath('/pool/source/dir')[0].get('path')
except:
except Exception:
raise ValueError('Source path not specified')
return result
@@ -360,7 +360,7 @@ class LibvirtConnection(object):
else:
try:
state = self.find_entry(entryid)
except:
except Exception:
return self.module.exit_json(changed=True)
if not state:
return self.module.exit_json(changed=True)
@@ -371,7 +371,7 @@ class LibvirtConnection(object):
else:
try:
state = self.find_entry(entryid)
except:
except Exception:
return self.module.exit_json(changed=True)
if state:
return self.module.exit_json(changed=True)
@@ -386,7 +386,7 @@ class LibvirtConnection(object):
else:
try:
return self.find_entry(entryid).autostart()
except:
except Exception:
return self.module.exit_json(changed=True)
def set_autostart(self, entryid, val):
@@ -395,7 +395,7 @@ class LibvirtConnection(object):
else:
try:
state = self.find_entry(entryid).autostart()
except:
except Exception:
return self.module.exit_json(changed=True)
if bool(state) != val:
return self.module.exit_json(changed=True)
@@ -413,7 +413,7 @@ class LibvirtConnection(object):
else:
try:
self.find_entry(entryid)
except:
except Exception:
return self.module.exit_json(changed=True)

View File

@@ -111,7 +111,7 @@ def main():
# Let's suppose user is passing domain ID
try:
domains = opcloud.get_domain(name)
except:
except Exception:
domains = opcloud.search_domains(filters={'name': name})
else:

View File

@@ -160,13 +160,13 @@ def main():
# We assume admin is passing domain id
dom = cloud.get_domain(domain)['id']
domain = dom
except:
except Exception:
# If we fail, maybe admin is passing a domain name.
# Note that domains have unique names, just like id.
try:
dom = cloud.search_domains(filters={'name': domain})[0]['id']
domain = dom
except:
except Exception:
# Ok, let's hope the user is non-admin and passing a sane id
pass

View File

@@ -127,7 +127,7 @@ def main():
# We assume admin is passing domain id
dom = opcloud.get_domain(domain)['id']
domain = dom
except:
except Exception:
# If we fail, maybe admin is passing a domain name.
# Note that domains have unique names, just like id.
dom = opcloud.search_domains(filters={'name': domain})

View File

@@ -160,12 +160,12 @@ def _get_domain_id(cloud, domain):
try:
# We assume admin is passing domain id
domain_id = cloud.get_domain(domain)['id']
except:
except Exception:
# If we fail, maybe admin is passing a domain name.
# Note that domains have unique names, just like id.
try:
domain_id = cloud.search_domains(filters={'name': domain})[0]['id']
except:
except Exception:
# Ok, let's hope the user is non-admin and passing a sane id
domain_id = domain

View File

@@ -135,7 +135,7 @@ def main():
# We assume admin is passing domain id
dom = opcloud.get_domain(domain)['id']
domain = dom
except:
except Exception:
# If we fail, maybe admin is passing a domain name.
# Note that domains have unique names, just like id.
dom = opcloud.search_domains(filters={'name': domain})

View File

@@ -332,7 +332,7 @@ def create(module, names=None, flavor=None, image=None, meta=None, key_name=None
for server in servers:
try:
server.get()
except:
except Exception:
server.status = 'ERROR'
if not filter(lambda s: s.status not in FINAL_STATUSES,
@@ -346,7 +346,7 @@ def create(module, names=None, flavor=None, image=None, meta=None, key_name=None
for server in servers:
try:
server.get()
except:
except Exception:
server.status = 'ERROR'
instance = rax_to_dict(server, 'server')
if server.status == 'ACTIVE' or not wait:
@@ -418,7 +418,7 @@ def delete(module, instance_ids=None, wait=True, wait_timeout=300, kept=None):
instance_id = server.id
try:
server.get()
except:
except Exception:
instances[instance_id]['status'] = 'DELETED'
instances[instance_id]['rax_status'] = 'DELETED'

View File

@@ -128,7 +128,7 @@ def rax_keypair(module, name, public_key, state):
elif state == 'absent':
try:
keypair = cs.keypairs.find(name=name)
except:
except Exception:
pass
if keypair:

View File

@@ -294,7 +294,7 @@ def wait_for_instance(module, id):
completed = vsManager.wait_for_ready(id, 10, 2)
if completed:
instance = vsManager.get_instance(id)
except:
except Exception:
completed = False
return completed, instance
@@ -310,12 +310,12 @@ def cancel_instance(module):
for instance in instances:
try:
vsManager.cancel_instance(instance['id'])
except:
except Exception:
canceled = False
elif module.params.get('instance_id') and module.params.get('instance_id') != 0:
try:
vsManager.cancel_instance(instance['id'])
except:
except Exception:
canceled = False
else:
return False, None

View File

@@ -143,7 +143,7 @@ def main():
grp.create()
else:
grp.modify()
except:
except Exception:
module.fail_json(
msg="Creating/editing group {} in {} failed".format(name, container)
)
@@ -154,7 +154,7 @@ def main():
if not module.check_mode:
grp.remove()
changed = True
except:
except Exception:
module.fail_json(
msg="Removing group {} failed".format(name)
)

View File

@@ -476,7 +476,7 @@ def main():
obj.create()
elif changed:
obj.modify()
except:
except Exception:
module.fail_json(
msg="Creating/editing user {} in {} failed".format(
username,
@@ -497,7 +497,7 @@ def main():
if not module.check_mode:
grp.modify()
changed = True
except:
except Exception:
module.fail_json(
msg="Adding groups to user {} failed".format(username)
)
@@ -508,7 +508,7 @@ def main():
if not module.check_mode:
obj.remove()
changed = True
except:
except Exception:
module.fail_json(
msg="Removing user {} failed".format(username)
)

View File

@@ -156,7 +156,7 @@ def main():
try:
lam = lm.licenseAssignmentManager
lam.UpdateAssignedLicense(entity=content.about.instanceUuid, licenseKey=license)
except:
except Exception:
module.warn('Could not assign "%s" (%s) to vCenter.' % (license, key.name))
result['licenses'] = list_keys(lm.licenses)

View File

@@ -181,7 +181,7 @@ class TarFileProgressReader(tarfile.ExFileObject):
def __exit__(self, exc_type, exc_value, traceback):
try:
self.close()
except:
except Exception:
pass
def read(self, size=10240):

View File

@@ -229,7 +229,7 @@ class VMwareResourcePool(object):
task = self.resource_pool_obj.Destroy()
success, result = wait_for_task(task)
except:
except Exception:
self.module.fail_json(msg="Failed to remove resource pool '%s' '%s'" % (
self.resource_pool, resource_pool))
self.module.exit_json(changed=changed, result=str(result))

View File

@@ -514,7 +514,7 @@ class ConsulCheck(object):
if attr is None:
attr = key
data[key] = getattr(self, attr)
except:
except Exception:
pass

View File

@@ -376,7 +376,7 @@ def main():
f.close()
if not data:
module.fail_json(msg="No valid data could be found.")
except:
except Exception:
module.fail_json(msg="The file '%s' was not found or contained invalid YAML/JSON data" % file_reference)
# set the transport type and build the target endpoint url

View File

@@ -131,7 +131,7 @@ def main():
# here we attempt to load those stats,
try:
stats = json.loads(stats_raw)
except:
except Exception:
module.fail_json(msg='Could not parse Riak stats.')
node_name = stats['nodename']

View File

@@ -111,7 +111,7 @@ def db_create(conn, cursor, db):
def db_delete(conn, cursor, db):
try:
cursor.execute("ALTER DATABASE [%s] SET single_user WITH ROLLBACK IMMEDIATE" % db)
except:
except Exception:
pass
cursor.execute("DROP DATABASE [%s]" % db)
return not db_exists(conn, cursor, db)

View File

@@ -139,7 +139,7 @@ def stop_slave(cursor):
try:
cursor.execute("STOP SLAVE")
stopped = True
except:
except Exception:
stopped = False
return stopped
@@ -148,7 +148,7 @@ def reset_slave(cursor):
try:
cursor.execute("RESET SLAVE")
reset = True
except:
except Exception:
reset = False
return reset
@@ -157,7 +157,7 @@ def reset_slave_all(cursor):
try:
cursor.execute("RESET SLAVE ALL")
reset = True
except:
except Exception:
reset = False
return reset
@@ -166,7 +166,7 @@ def start_slave(cursor):
try:
cursor.execute("START SLAVE")
started = True
except:
except Exception:
started = False
return started

View File

@@ -588,7 +588,7 @@ def main():
try:
cursor = mysql_connect(module, 'root', '', config_file, ssl_cert, ssl_key, ssl_ca, db,
connect_timeout=connect_timeout)
except:
except Exception:
pass
if not cursor:

View File

@@ -181,7 +181,7 @@ def lang_drop(cursor, lang, cascade):
cursor.execute("DROP LANGUAGE \"%s\" CASCADE" % lang)
else:
cursor.execute("DROP LANGUAGE \"%s\"" % lang)
except:
except Exception:
cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_lang_drop")
cursor.execute("RELEASE SAVEPOINT ansible_pgsql_lang_drop")
return False

View File

@@ -466,7 +466,7 @@ def user_delete(cursor, user):
cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
try:
cursor.execute("DROP USER %s" % pg_quote_identifier(user, 'role'))
except:
except Exception:
cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
return False

View File

@@ -532,7 +532,7 @@ def main():
mimetype, charset = out.split(':')[1].split(';')
output['mimetype'] = mimetype.strip()
output['charset'] = charset.split('=')[1].strip()
except:
except Exception:
pass
# try to get attr data

View File

@@ -241,7 +241,7 @@ class ZipArchive(object):
try:
for item in archive.infolist():
self._infodict[item.filename] = int(item.CRC)
except:
except Exception:
archive.close()
raise UnarchiveError('Unable to list files in the archive')
@@ -273,7 +273,7 @@ class ZipArchive(object):
break
if not exclude_flag:
self._files_in_archive.append(to_native(member))
except:
except Exception:
archive.close()
raise UnarchiveError('Unable to list files in the archive')
@@ -328,7 +328,7 @@ class ZipArchive(object):
else:
try:
fut_owner = run_owner
except:
except Exception:
pass
fut_uid = run_uid
@@ -347,7 +347,7 @@ class ZipArchive(object):
else:
try:
fut_group = run_group
except:
except Exception:
pass
fut_gid = run_gid
@@ -427,7 +427,7 @@ class ZipArchive(object):
dest = os.path.join(self.dest, path)
try:
st = os.lstat(dest)
except:
except Exception:
change = True
self.includes.append(path)
err += 'Path %s is missing\n' % path

View File

@@ -96,7 +96,7 @@ import traceback
try:
from datadog import initialize, api
HAS_DATADOG = True
except:
except Exception:
HAS_DATADOG = False
from ansible.module_utils.basic import AnsibleModule

View File

@@ -144,7 +144,7 @@ import traceback
try:
from datadog import initialize, api
HAS_DATADOG = True
except:
except Exception:
HAS_DATADOG = False
from ansible.module_utils.basic import AnsibleModule

View File

@@ -867,7 +867,7 @@ class Collector(LogicMonitor):
"arch": arch}))
with open(installfilepath, "w") as write_file:
write_file.write(installer)
except:
except Exception:
self.fail(msg="Unable to open installer file for writing")
else:
self.module.debug("Collector installer already exists")

View File

@@ -222,7 +222,7 @@ class PagerDutyRequest(object):
def _read_response(self, response):
try:
return json.loads(response.read())
except:
except Exception:
return ""

View File

@@ -71,7 +71,7 @@ EXAMPLES = '''
try:
import pingdom
HAS_PINGDOM = True
except:
except Exception:
HAS_PINGDOM = False
from ansible.module_utils.basic import AnsibleModule

View File

@@ -130,7 +130,7 @@ def query(module, url, check, subscription):
try:
json_out = json.loads(response.read())
except:
except Exception:
json_out = ""
return False, json_out, False
@@ -182,7 +182,7 @@ def clear(module, url, check, subscription):
try:
json_out = json.loads(response.read())
except:
except Exception:
json_out = ""
return False, json_out, True
@@ -247,7 +247,7 @@ def create(
try:
json_out = json.loads(response.read())
except:
except Exception:
json_out = ""
return False, json_out, True

View File

@@ -588,7 +588,7 @@ def main():
try:
js = json.loads(u_content)
uresp['json'] = js
except:
except Exception:
if PY2:
sys.exc_clear() # Avoid false positive traceback in fail_json() on Python 2
else:

View File

@@ -173,7 +173,7 @@ import json
try:
import pynetbox
HAS_PYNETBOX = True
except:
except ImportError:
HAS_PYNETBOX = False

View File

@@ -632,7 +632,7 @@ class Nmcli(object):
for setting in secrets:
for key in secrets[setting]:
config[setting_name][key] = secrets[setting][key]
except:
except Exception:
pass
def dict_to_string(self, d):

View File

@@ -169,7 +169,7 @@ from collections import defaultdict
try:
from pysnmp.entity.rfc3413.oneliner import cmdgen
has_pysnmp = True
except:
except Exception:
has_pysnmp = False
from ansible.module_utils.basic import AnsibleModule

View File

@@ -117,7 +117,7 @@ def validate_ports(module, ports):
if 'port_num' in item:
try:
item['port_num'] = int(item['port_num'])
except:
except Exception:
module.fail_json(msg="port_num entries in the port definitions must be integers")
else:
module.fail_json(msg="port definitions must define the port_num field")

View File

@@ -108,7 +108,7 @@ def validate_ports(module, ports):
if 'port-number' in item:
try:
item['port-number'] = int(item['port-number'])
except:
except Exception:
module.fail_json(msg="port-number entries in the port definitions must be integers")
else:
module.fail_json(msg="port definitions must define the port-number field")

View File

@@ -137,7 +137,7 @@ def validate_servers(module, servers):
if 'port' in item:
try:
item['port'] = int(item['port'])
except:
except Exception:
module.fail_json(msg="server port definitions must be integers")
else:
module.fail_json(msg="server definitions must define the port field")

View File

@@ -119,7 +119,7 @@ def validate_ports(module, ports):
if 'port' in item:
try:
item['port'] = int(item['port'])
except:
except Exception:
module.fail_json(msg="port definitions must be integers")
else:
module.fail_json(msg="port definitions must define the port field")

View File

@@ -242,7 +242,7 @@ import os
try:
from ansible.module_utils.six.moves.urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
HAS_URLPARSE = True
except:
except Exception:
HAS_URLPARSE = False
# Optional, only used for XML payload
@@ -263,7 +263,7 @@ except ImportError:
try:
import yaml
HAS_YAML = True
except:
except Exception:
HAS_YAML = False
from ansible.module_utils.basic import AnsibleModule

View File

@@ -209,7 +209,7 @@ def asn_pool_absent(module, aos, my_pool):
if not module.check_mode:
try:
my_pool.delete()
except:
except Exception:
module.fail_json(msg="An error occurred, while trying to delete the ASN Pool")
module.exit_json(changed=True,
@@ -240,7 +240,7 @@ def asn_pool_present(module, aos, my_pool):
try:
my_new_pool = create_new_asn_pool(my_pool, margs['name'], margs['ranges'])
my_pool = my_new_pool
except:
except Exception:
module.fail_json(msg="An error occurred while trying to create a new ASN Pool ")
module.exit_json(changed=True,
@@ -271,7 +271,7 @@ def asn_pool(module):
try:
aos = get_aos_session(module, margs['session'])
except:
except Exception:
module.fail_json(msg="Unable to login to the AOS server")
item_name = False
@@ -304,7 +304,7 @@ def asn_pool(module):
my_pool = find_collection_item(aos.AsnPools,
item_name=item_name,
item_id=item_id)
except:
except Exception:
module.fail_json(msg="Unable to find the IP Pool based on name or ID, something went wrong")
# ----------------------------------------------------

View File

@@ -234,7 +234,7 @@ def aos_blueprint(module):
try:
aos = get_aos_session(module, margs['session'])
except:
except Exception:
module.fail_json(msg="Unable to login to the AOS server")
item_name = False
@@ -253,7 +253,7 @@ def aos_blueprint(module):
my_blueprint = find_collection_item(aos.Blueprints,
item_name=item_name,
item_id=item_id)
except:
except Exception:
module.fail_json(msg="Unable to find the Blueprint based on name or ID, something went wrong")
# ----------------------------------------------------

View File

@@ -207,7 +207,7 @@ def get_collection_from_param_map(module, aos):
try:
param_map = yaml.safe_load(param_map_json)
except:
except Exception:
module.fail_json(msg="Unable to parse param_map information")
else:
@@ -292,7 +292,7 @@ def blueprint_param(module):
# --------------------------------------------------------------------
try:
aos = get_aos_session(module, margs['session'])
except:
except Exception:
module.fail_json(msg="Unable to login to the AOS server")
# --------------------------------------------------------------------
@@ -302,7 +302,7 @@ def blueprint_param(module):
blueprint = find_collection_item(aos.Blueprints,
item_name=margs['blueprint'],
item_id=margs['blueprint'])
except:
except Exception:
module.fail_json(msg="Unable to find the Blueprint based on name or ID, something went wrong")
if blueprint.exists is False:

View File

@@ -143,7 +143,7 @@ def blueprint_virtnet(module):
# --------------------------------------------------------------------
try:
aos = get_aos_session(module, margs['session'])
except:
except Exception:
module.fail_json(msg="Unable to login to the AOS server")
# --------------------------------------------------------------------
@@ -153,7 +153,7 @@ def blueprint_virtnet(module):
blueprint = find_collection_item(aos.Blueprints,
item_name=margs['blueprint'],
item_id=margs['blueprint'])
except:
except Exception:
module.fail_json(msg="Unable to find the Blueprint based on name or ID, something went wrong")
if blueprint.exists is False:
@@ -181,7 +181,7 @@ def blueprint_virtnet(module):
# --------------------------------------------------------------------
try:
virtnet = blueprint.VirtualNetworks[item_name]
except:
except Exception:
module.fail_json(msg="Something went wrong while trying to find Virtual Network %s in blueprint %s"
% (item_name, blueprint.name))

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