Skip to content

Commit

Permalink
Mass-migration over to is_boto3_error_code
Browse files Browse the repository at this point in the history
  • Loading branch information
tremble committed Oct 20, 2020
1 parent 0a27968 commit 375d92f
Show file tree
Hide file tree
Showing 38 changed files with 275 additions and 343 deletions.
8 changes: 3 additions & 5 deletions plugins/modules/aws_glue_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
'''

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_ec2_security_group_ids_from_names

Expand Down Expand Up @@ -161,11 +162,8 @@ def _get_glue_connection(connection, module):

try:
return connection.get_connection(**params)['Connection']
except (BotoCoreError, ClientError) as e:
if e.response['Error']['Code'] == 'EntityNotFoundException':
return None
else:
raise e
except is_boto3_error_code('EntityNotFoundException'):
return None


def _compare_glue_connection_params(user_params, current_params):
Expand Down
10 changes: 5 additions & 5 deletions plugins/modules/aws_glue_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@
pass # Handled by AnsibleAWSModule

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict


Expand All @@ -208,11 +209,10 @@ def _get_glue_job(connection, module, glue_job_name):

try:
return connection.get_job(JobName=glue_job_name)['Job']
except (BotoCoreError, ClientError) as e:
if e.response['Error']['Code'] == 'EntityNotFoundException':
return None
else:
module.fail_json_aws(e)
except is_boto3_error_code('EntityNotFoundException'):
return None
except (BotoCoreError, ClientError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e)


def _compare_glue_job_params(user_params, current_params):
Expand Down
18 changes: 8 additions & 10 deletions plugins/modules/aws_kms_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,11 +305,10 @@ def get_kms_tags(connection, module, key_id):
try:
tag_response = get_kms_tags_with_backoff(connection, key_id, **kwargs)
tags.extend(tag_response['Tags'])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] != 'AccessDeniedException':
module.fail_json_aws(e, msg="Failed to obtain key tags")
else:
tag_response = {}
except is_boto3_error_code('AccessDeniedException'):
tag_response = {}
except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Failed to obtain key tags")
if tag_response.get('NextMarker'):
kwargs['Marker'] = tag_response['NextMarker']
else:
Expand All @@ -322,11 +321,10 @@ def get_kms_policies(connection, module, key_id):
policies = list_key_policies_with_backoff(connection, key_id)['PolicyNames']
return [get_key_policy_with_backoff(connection, key_id, policy)['Policy'] for
policy in policies]
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] != 'AccessDeniedException':
module.fail_json_aws(e, msg="Failed to obtain key policies")
else:
return []
except is_boto3_error_code('AccessDeniedException'):
return []
except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Failed to obtain key policies")


def key_matches_filter(key, filtr):
Expand Down
7 changes: 4 additions & 3 deletions plugins/modules/aws_ssm_parameter_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
pass # Handled by AnsibleAWSModule

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code


def update_parameter(client, module, args):
Expand Down Expand Up @@ -213,9 +214,9 @@ def delete_parameter(client, module):
response = client.delete_parameter(
Name=module.params.get('name')
)
except ClientError as e:
if e.response['Error']['Code'] == 'ParameterNotFound':
return False, {}
except is_boto3_error_code('ParameterNotFound'):
return False, {}
except ClientError as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="deleting parameter")

return True, response
Expand Down
9 changes: 5 additions & 4 deletions plugins/modules/aws_step_functions_state_machine_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@


from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict

try:
Expand Down Expand Up @@ -123,10 +124,10 @@ def start_execution(module, sfn_client):
name=name,
input=execution_input
)
except (ClientError, BotoCoreError) as e:
if e.response['Error']['Code'] == 'ExecutionAlreadyExists':
# this will never be executed anymore
module.exit_json(changed=False)
except is_boto3_error_code('ExecutionAlreadyExists'):
# this will never be executed anymore
module.exit_json(changed=False)
except (ClientError, BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Failed to start execution.")

module.exit_json(changed=True, **camel_dict_to_snake_dict(res_execution))
Expand Down
7 changes: 4 additions & 3 deletions plugins/modules/aws_waf_condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@
pass # handled by AnsibleAWSModule

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import compare_policies
Expand Down Expand Up @@ -545,9 +546,9 @@ def delete_unused_regex_pattern(self, regex_pattern_set_id):
run_func_with_change_token_backoff(self.client, self.module,
{'RegexPatternSetId': regex_pattern_set_id},
self.client.delete_regex_pattern_set, wait=True)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
if e.response['Error']['Code'] == 'WAFNonexistentItemException':
return
except is_boto3_error_code('WAFNonexistentItemException'):
return
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except
self.module.fail_json_aws(e, msg='Could not delete regex pattern')

def get_condition_by_name(self, name):
Expand Down
19 changes: 7 additions & 12 deletions plugins/modules/cloudwatchevent_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@
pass # handled by AnsibleAWSModule

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict


Expand All @@ -174,12 +175,9 @@ def describe(self):
"""Returns the existing details of the rule in AWS"""
try:
rule_info = self.client.describe_rule(Name=self.name)
except botocore.exceptions.ClientError as e:
error_code = e.response.get('Error', {}).get('Code')
if error_code == 'ResourceNotFoundException':
return {}
self.module.fail_json_aws(e, msg="Could not describe rule %s" % self.name)
except botocore.exceptions.BotoCoreError as e:
except is_boto3_error_code('ResourceNotFoundException'):
return {}
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except
self.module.fail_json_aws(e, msg="Could not describe rule %s" % self.name)
return self._snakify(rule_info)

Expand Down Expand Up @@ -237,12 +235,9 @@ def list_targets(self):
"""Lists the existing targets for the rule in AWS"""
try:
targets = self.client.list_targets_by_rule(Rule=self.name)
except botocore.exceptions.ClientError as e:
error_code = e.response.get('Error', {}).get('Code')
if error_code == 'ResourceNotFoundException':
return []
self.module.fail_json_aws(e, msg="Could not find target for rule %s" % self.name)
except botocore.exceptions.BotoCoreError as e:
except is_boto3_error_code('ResourceNotFoundException'):
return []
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: # pylint: disable=duplicate-except
self.module.fail_json_aws(e, msg="Could not find target for rule %s" % self.name)
return self._snakify(targets)['targets']

Expand Down
6 changes: 3 additions & 3 deletions plugins/modules/data_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@
from ansible.module_utils._text import to_text

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict


Expand Down Expand Up @@ -361,9 +362,8 @@ def activate_pipeline(client, module):
else:
try:
client.activate_pipeline(pipelineId=dp_id)
except ClientError as e:
if e.response["Error"]["Code"] == "InvalidRequestException":
module.fail_json(msg="You need to populate your pipeline before activation.")
except is_boto3_error_code('InvalidRequestException'):
module.fail_json(msg="You need to populate your pipeline before activation.")
try:
pipeline_status_timeout(client, dp_id, status=DP_ACTIVE_STATES,
timeout=timeout)
Expand Down
19 changes: 7 additions & 12 deletions plugins/modules/ec2_asg.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,7 @@

from ansible.module_utils._text import to_native
from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict

Expand Down Expand Up @@ -851,12 +852,9 @@ def elb_healthy(asg_connection, elb_connection, group_name):
# but has not yet show up in the ELB
try:
lb_instances = describe_instance_health(elb_connection, lb, instances)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidInstance':
return None

module.fail_json_aws(e, msg="Failed to get load balancer.")
except botocore.exceptions.BotoCoreError as e:
except is_boto3_error_code('InvalidInstance'):
return None
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Failed to get load balancer.")

for i in lb_instances.get('InstanceStates'):
Expand All @@ -883,12 +881,9 @@ def tg_healthy(asg_connection, elbv2_connection, group_name):
# but has not yet show up in the ELB
try:
tg_instances = describe_target_health(elbv2_connection, tg, instances)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidInstance':
return None

module.fail_json_aws(e, msg="Failed to get target group.")
except botocore.exceptions.BotoCoreError as e:
except is_boto3_error_code('InvalidInstance'):
return None
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Failed to get target group.")

for i in tg_instances.get('TargetHealthDescriptions'):
Expand Down
10 changes: 4 additions & 6 deletions plugins/modules/ec2_asg_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
pass # caught by AnsibleAWSModule

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import camel_dict_to_snake_dict


Expand Down Expand Up @@ -373,12 +374,9 @@ def find_asgs(conn, module, name=None, tags=None):
tg_paginator = elbv2.get_paginator('describe_target_groups')
tg_result = tg_paginator.paginate(TargetGroupArns=asg['target_group_arns']).build_full_result()
asg['target_group_names'] = [tg['TargetGroupName'] for tg in tg_result['TargetGroups']]
except ClientError as e:
if e.response['Error']['Code'] == 'TargetGroupNotFound':
asg['target_group_names'] = []
else:
module.fail_json_aws(e, msg="Failed to describe Target Groups")
except BotoCoreError as e:
except is_boto3_error_code('TargetGroupNotFound'):
asg['target_group_names'] = []
except (ClientError, BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Failed to describe Target Groups")
else:
asg['target_group_names'] = []
Expand Down
21 changes: 10 additions & 11 deletions plugins/modules/ec2_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,7 @@

import ansible_collections.amazon.aws.plugins.module_utils.ec2 as ec2_utils
from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_message
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list
Expand Down Expand Up @@ -1116,15 +1117,13 @@ def discover_security_groups(group, groups, parent_vpc_id=None, subnet_id=None,
if subnet_id is not None:
try:
sub = ec2.describe_subnets(SubnetIds=[subnet_id])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidGroup.NotFound':
module.fail_json(
"Could not find subnet {0} to associate security groups. Please check the vpc_subnet_id and security_groups parameters.".format(
subnet_id
)
except is_boto3_error_code('InvalidGroup.NotFound'):
module.fail_json(
"Could not find subnet {0} to associate security groups. Please check the vpc_subnet_id and security_groups parameters.".format(
subnet_id
)
module.fail_json_aws(e, msg="Error while searching for subnet {0} parent VPC.".format(subnet_id))
except botocore.exceptions.BotoCoreError as e:
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Error while searching for subnet {0} parent VPC.".format(subnet_id))
parent_vpc_id = sub['Subnets'][0]['VpcId']

Expand Down Expand Up @@ -1609,9 +1608,9 @@ def determine_iam_role(name_or_arn):
try:
role = iam.get_instance_profile(InstanceProfileName=name_or_arn, aws_retry=True)
return role['InstanceProfile']['Arn']
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntity':
module.fail_json_aws(e, msg="Could not find instance_role {0}".format(name_or_arn))
except is_boto3_error_code('NoSuchEntity'):
module.fail_json_aws(e, msg="Could not find instance_role {0}".format(name_or_arn))
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="An error occurred while searching for instance_role {0}. Please try supplying the full ARN.".format(name_or_arn))


Expand Down
15 changes: 8 additions & 7 deletions plugins/modules/ec2_placement_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
pass # caught by AnsibleAWSModule

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry


Expand Down Expand Up @@ -129,13 +130,13 @@ def create_placement_group(connection, module):
try:
connection.create_placement_group(
GroupName=name, Strategy=strategy, DryRun=module.check_mode)
except (BotoCoreError, ClientError) as e:
if e.response['Error']['Code'] == "DryRunOperation":
module.exit_json(changed=True, placement_group={
"name": name,
"state": 'DryRun',
"strategy": strategy,
})
except is_boto3_error_code('DryRunOperation'):
module.exit_json(changed=True, placement_group={
"name": name,
"state": 'DryRun',
"strategy": strategy,
})
except (ClientError, BotoCoreError) as e: # pylint: disable=duplicate-except
module.fail_json_aws(
e,
msg="Couldn't create placement group [%s]" % name)
Expand Down
9 changes: 4 additions & 5 deletions plugins/modules/ec2_transit_gateway_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@
pass # handled by imported AnsibleAWSModule

from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.core import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ansible_dict_to_boto3_filter_list
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import boto3_tag_list_to_ansible_dict
Expand Down Expand Up @@ -206,11 +207,9 @@ def describe_transit_gateways(self):
try:
response = self._connection.describe_transit_gateways(
TransitGatewayIds=transit_gateway_ids, Filters=filters)
except ClientError as e:
if e.response['Error']['Code'] == 'InvalidTransitGatewayID.NotFound':
self._results['transit_gateways'] = []
return
raise
except is_boto3_error_code('InvalidTransitGatewayID.NotFound'):
self._results['transit_gateways'] = []
return

for transit_gateway in response['TransitGateways']:
transit_gateway_info.append(camel_dict_to_snake_dict(transit_gateway, ignore_list=['Tags']))
Expand Down
Loading

0 comments on commit 375d92f

Please sign in to comment.