Skip to content

Commit

Permalink
Minor sanity test fixes - new devel sanity tests (#968)
Browse files Browse the repository at this point in the history
Minor sanity test fixes (new devel)

SUMMARY
ansible-devel has added a new PEP test (missing whitespace after keyword), this adds the fixes before the devel sanity tests are 'voting'.
Additionally fixes:

unused variables
broad catching of Exception

ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
plugins/action/s3_object.py
plugins/module_utils/elbv2.py
plugins/module_utils/waf.py
plugins/modules/aws_caller_info.py
plugins/modules/cloudformation.py
plugins/modules/ec2_metadata_facts.py
plugins/modules/ec2_security_group.py
plugins/modules/ec2_vpc_endpoint.py
plugins/modules/ec2_vpc_nat_gateway.py
ADDITIONAL INFORMATION

Reviewed-by: Alina Buzachis <None>
  • Loading branch information
tremble authored Aug 15, 2022
1 parent f4e81e9 commit 315472a
Show file tree
Hide file tree
Showing 10 changed files with 25 additions and 17 deletions.
8 changes: 8 additions & 0 deletions changelogs/fragments/968-sanity.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
minor_changes:
- s3_object - minor linting fixes (https://github.com/ansible-collections/amazon.aws/pull/968).
- aws_caller_info - minor linting fixes (https://github.com/ansible-collections/amazon.aws/pull/968).
- cloudformation - avoid catching ``Exception``, catch more specific errors instead (https://github.com/ansible-collections/amazon.aws/pull/968).
- ec2_metadata_facts - avoid catching ``Exception``, catch more specific errors instead (https://github.com/ansible-collections/amazon.aws/pull/968).
- ec2_security_group - minor linting fixes (https://github.com/ansible-collections/amazon.aws/pull/968).
- ec2_vpc_endpoint - avoid catching ``Exception``, catch more specific errors instead (https://github.com/ansible-collections/amazon.aws/pull/968).
- ec2_vpc_nat_gateway - minor linting fixes (https://github.com/ansible-collections/amazon.aws/pull/968).
2 changes: 1 addition & 1 deletion plugins/action/s3_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def run(self, tmp=None, task_vars=None):
try:
source = self._loader.get_real_file(self._find_needle('files', source), decrypt=False)
new_module_args['src'] = source
except AnsibleFileNotFound as e:
except AnsibleFileNotFound:
# module handles error message for nonexistent files
new_module_args['src'] = source
except AnsibleError as e:
Expand Down
2 changes: 1 addition & 1 deletion plugins/module_utils/elbv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def _prune_ForwardConfig(action):

# Remove the redundant ForwardConfig
newAction = action.copy()
del(newAction["ForwardConfig"])
del newAction["ForwardConfig"]
newAction["TargetGroupArn"] = arn
return newAction

Expand Down
2 changes: 1 addition & 1 deletion plugins/module_utils/waf.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def get_rule(client, module, rule_id):
if predicate['Type'] in match_sets:
predicate.update(match_sets[predicate['Type']](client, predicate['DataId']))
# replaced by Id from the relevant MatchSet
del(predicate['DataId'])
del predicate['DataId']
return rule


Expand Down
2 changes: 1 addition & 1 deletion plugins/modules/aws_caller_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def main():
caller_info['account_alias'] = response['AccountAliases'][0]
else:
caller_info['account_alias'] = ''
except (BotoCoreError, ClientError) as e:
except (BotoCoreError, ClientError):
# The iam:ListAccountAliases permission is required for this operation to succeed.
# Lacking this permission is handled gracefully by not returning the account_alias.
pass
Expand Down
10 changes: 5 additions & 5 deletions plugins/modules/cloudformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ def create_stack(module, stack_params, cfn, events_limit):
response = cfn.create_stack(aws_retry=True, **stack_params)
# Use stack ID to follow stack state in case of on_create_failure = DELETE
result = stack_operation(module, cfn, response['StackId'], 'CREATE', events_limit, stack_params.get('ClientRequestToken', None))
except Exception as err:
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err:
module.fail_json_aws(err, msg="Failed to create stack {0}".format(stack_params.get('StackName')))
if not result:
module.fail_json(msg="empty result")
Expand Down Expand Up @@ -459,7 +459,7 @@ def create_changeset(module, stack_params, cfn, events_limit):
'NOTE that dependencies on this stack might fail due to pending changes!']
except is_boto3_error_message('No updates are to be performed.'):
result = dict(changed=False, output='Stack is already up-to-date.')
except Exception as err:
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err:
module.fail_json_aws(err, msg='Failed to create change set')

if not result:
Expand All @@ -482,7 +482,7 @@ def update_stack(module, stack_params, cfn, events_limit):
result = stack_operation(module, cfn, stack_params['StackName'], 'UPDATE', events_limit, stack_params.get('ClientRequestToken', None))
except is_boto3_error_message('No updates are to be performed.'):
result = dict(changed=False, output='Stack is already up-to-date.')
except Exception as err:
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err:
module.fail_json_aws(err, msg="Failed to update stack {0}".format(stack_params.get('StackName')))
if not result:
module.fail_json(msg="empty result")
Expand Down Expand Up @@ -510,7 +510,7 @@ def stack_operation(module, cfn, stack_name, operation, events_limit, op_token=N
try:
stack = get_stack_facts(module, cfn, stack_name, raise_errors=True)
existed.append('yes')
except Exception:
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError):
# 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.
Expand Down Expand Up @@ -783,7 +783,7 @@ def main():
cfn.delete_stack(aws_retry=True, StackName=stack_params['StackName'], RoleARN=stack_params['RoleARN'])
result = stack_operation(module, cfn, stack_params['StackName'], 'DELETE', module.params.get('events_limit'),
stack_params.get('ClientRequestToken', None))
except Exception as err:
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err:
module.fail_json_aws(err)

module.exit_json(**result)
Expand Down
6 changes: 3 additions & 3 deletions plugins/modules/ec2_metadata_facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,11 +524,11 @@ def fetch(self, uri, recurse=True):
self._data['%s' % (new_uri)] = sg_fields
else:
try:
dict = json.loads(content)
json_dict = json.loads(content)
self._data['%s' % (new_uri)] = content
for (key, value) in dict.items():
for (key, value) in json_dict.items():
self._data['%s:%s' % (new_uri, key.lower())] = value
except Exception:
except json.JSONDecodeError:
self._data['%s' % (new_uri)] = content # not a stringified JSON string

def fix_invalid_varnames(self, data):
Expand Down
2 changes: 1 addition & 1 deletion plugins/modules/ec2_security_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,7 +759,7 @@ def get_target_from_rule(module, client, rule, name, group, groups, vpc_id):
# the model on their end.
try:
auto_group = get_security_groups_with_backoff(client, Filters=ansible_dict_to_boto3_filter_list(filters)).get('SecurityGroups', [])[0]
except IndexError as e:
except IndexError:
module.fail_json(msg="Could not create or use existing group '{0}' in rule. Make sure the group exists".format(group_name))
except ClientError as e:
module.fail_json_aws(
Expand Down
2 changes: 1 addition & 1 deletion plugins/modules/ec2_vpc_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ def create_vpc_endpoint(client, module):
try:
with open(module.params.get('policy_file'), 'r') as json_data:
policy = json.load(json_data)
except Exception as e:
except (OSError, json.JSONDecodeError) as e:
module.fail_json(msg=str(e), exception=traceback.format_exc(),
**camel_dict_to_snake_dict(e.response))

Expand Down
6 changes: 3 additions & 3 deletions plugins/modules/ec2_vpc_nat_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,15 +444,15 @@ def get_eip_allocation_id_by_address(client, module, eip_address):
else:
allocation_id = allocation.get('AllocationId')

except is_boto3_error_code('InvalidAddress.Malformed') as e:
except is_boto3_error_code('InvalidAddress.Malformed'):
module.fail_json(msg='EIP address {0} is invalid.'.format(eip_address))
except is_boto3_error_code('InvalidAddress.NotFound') as e: # pylint: disable=duplicate-except
except is_boto3_error_code('InvalidAddress.NotFound'): # pylint: disable=duplicate-except
msg = (
"EIP {0} does not exist".format(eip_address)
)
allocation_id = None
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e)
module.fail_json_aws(e, msg="Unable to describe EIP")

return allocation_id, msg

Expand Down

0 comments on commit 315472a

Please sign in to comment.