Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor typing fixups #2497

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelogs/fragments/20250202-typealias.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
bugfixes:
- module_utils.botocore - fixed type aliasing (https://github.com/ansible-collections/amazon.aws/pull/2497).
- plugin_utils.botocore - fixed type aliasing (https://github.com/ansible-collections/amazon.aws/pull/2497).
minor_changes:
- module_utils._s3 - explicitly cast super to the parent type (https://github.com/ansible-collections/amazon.aws/pull/2497).
- module_utils.botocore - avoid assigning unused parts of exc_info return (https://github.com/ansible-collections/amazon.aws/pull/2497).
- module_utils.exceptions - avoid assigning unused parts of exc_info return (https://github.com/ansible-collections/amazon.aws/pull/2497).
3 changes: 2 additions & 1 deletion plugins/module_utils/_s3/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from __future__ import annotations

import functools
from typing import cast

try:
# Beware, S3 is a "special" case, it sometimes catches botocore exceptions and
Expand Down Expand Up @@ -67,7 +68,7 @@ def _is_missing(cls):
@classmethod
def common_error_handler(cls, description):
def wrapper(func):
parent_class = super(S3ErrorHandler, cls)
parent_class = cast(AWSErrorHandler, super(S3ErrorHandler, cls))

@parent_class.common_error_handler(description)
@functools.wraps(func)
Expand Down
40 changes: 19 additions & 21 deletions plugins/module_utils/botocore.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

import json
import os
import sys
import traceback
import typing
from typing import Any
Expand All @@ -53,15 +54,18 @@
try:
import boto3
import botocore
from botocore.exceptions import ClientError

HAS_BOTO3 = True
except ImportError:
BOTO3_IMP_ERR = traceback.format_exc()
HAS_BOTO3 = False

if typing.TYPE_CHECKING:
ClientType = botocore.client.BaseClient
ResourceType = boto3.resources.base.ServiceResource
from typing_extensions import TypeAlias

ClientType: TypeAlias = botocore.client.BaseClient
ResourceType: TypeAlias = boto3.resources.base.ServiceResource
BotoConn = Union[ClientType, ResourceType, Tuple[ClientType, ResourceType]]
from .modules import AnsibleAWSModule

Expand Down Expand Up @@ -114,6 +118,7 @@ def boto3_conn(
return _boto3_conn(conn_type=conn_type, resource=resource, region=region, endpoint=endpoint, **params)
except botocore.exceptions.NoRegionError:
module.fail_json(
# pylint: disable-next=protected-access
msg=f"The {module._name} module requires a region and none was found in configuration, "
"environment variables or module parameters",
)
Expand Down Expand Up @@ -228,7 +233,7 @@ def _aws_region(params: Dict) -> Optional[str]:

def get_aws_region(
module: AnsibleAWSModule,
) -> Optional[str]: # pylint: disable=redefined-outer-name
) -> Optional[str]:
try:
return _aws_region(module.params)
except AnsibleBotocoreError as e:
Expand Down Expand Up @@ -294,7 +299,7 @@ def _aws_connection_info(params: Dict) -> Tuple[Optional[str], Optional[str], Di

def get_aws_connection_info(
module: AnsibleAWSModule,
) -> Tuple[Optional[str], Optional[str], Dict]: # pylint: disable=redefined-outer-name
) -> Tuple[Optional[str], Optional[str], Dict]:
try:
return _aws_connection_info(module.params)
except AnsibleBotocoreError as e:
Expand Down Expand Up @@ -369,12 +374,8 @@ def is_boto3_error_code(
except botocore.exceptions.ClientError as e:
# handle the generic error case for all other codes
"""
from botocore.exceptions import ClientError

if e is None:
import sys

dummy, e, dummy = sys.exc_info()
e = sys.exc_info()[1]
if not isinstance(code, (list, tuple, set)):
code = [code]
if isinstance(e, ClientError) and e.response["Error"]["Code"] in code:
Expand All @@ -398,12 +399,9 @@ def is_boto3_error_message(
except botocore.exceptions.ClientError as e:
# handle the generic error case for all other codes
"""
from botocore.exceptions import ClientError

if e is None:
import sys

dummy, e, dummy = sys.exc_info()
e = sys.exc_info()[1]
if isinstance(e, ClientError) and msg in e.response["Error"]["Message"]:
return ClientError
return type("NeverEverRaisedException", (Exception,), {})
Expand All @@ -415,7 +413,7 @@ def get_boto3_client_method_parameters(
required=False,
) -> List:
op = client.meta.method_to_api_mapping.get(method_name)
input_shape = client._service_model.operation_model(op).input_shape
input_shape = client._service_model.operation_model(op).input_shape # pylint: disable=protected-access
if not input_shape:
parameters = []
elif required:
Expand Down Expand Up @@ -450,12 +448,12 @@ def enable_placebo(session: boto3.session.Session) -> None:
"""
Helper to record or replay offline modules for testing purpose.
"""
# pylint: disable=import-outside-toplevel
if "_ANSIBLE_PLACEBO_RECORD" in os.environ:
import placebo

existing_entries = os.listdir(os.environ["_ANSIBLE_PLACEBO_RECORD"])
idx = len(existing_entries)
data_path = f"{os.environ['_ANSIBLE_PLACEBO_RECORD']}/{idx}"
recorded_entries = os.listdir(os.environ["_ANSIBLE_PLACEBO_RECORD"])
data_path = f"{os.environ['_ANSIBLE_PLACEBO_RECORD']}/{len(recorded_entries)}"
os.mkdir(data_path)
pill = placebo.attach(session, data_path=data_path)
pill.record()
Expand All @@ -464,18 +462,18 @@ def enable_placebo(session: boto3.session.Session) -> None:

import placebo

existing_entries = sorted([int(i) for i in os.listdir(os.environ["_ANSIBLE_PLACEBO_REPLAY"])])
idx = str(existing_entries[0])
data_path = os.environ["_ANSIBLE_PLACEBO_REPLAY"] + "/" + idx
replay_entries = sorted([int(i) for i in os.listdir(os.environ["_ANSIBLE_PLACEBO_REPLAY"])])
data_path = f"{os.environ['_ANSIBLE_PLACEBO_REPLAY']}/{replay_entries[0]}"
try:
shutil.rmtree("_tmp")
except FileNotFoundError:
pass
shutil.move(data_path, "_tmp")
if len(existing_entries) == 1:
if len(replay_entries) == 1:
os.rmdir(os.environ["_ANSIBLE_PLACEBO_REPLAY"])
pill = placebo.attach(session, data_path="_tmp")
pill.playback()
# pylint: enable=import-outside-toplevel


def check_sdk_version_supported(
Expand Down
4 changes: 2 additions & 2 deletions plugins/module_utils/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def is_ansible_aws_error_code(code, e=None):
if e is None:
import sys

dummy, e, dummy = sys.exc_info()
e = sys.exc_info()[1]
if not isinstance(code, (list, tuple, set)):
code = [code]
if (
Expand Down Expand Up @@ -79,7 +79,7 @@ def is_ansible_aws_error_message(msg, e=None):
if e is None:
import sys

dummy, e, dummy = sys.exc_info()
e = sys.exc_info()[1]
if (
isinstance(e, AnsibleAWSError)
and e.exception
Expand Down
6 changes: 4 additions & 2 deletions plugins/plugin_utils/botocore.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@
from typing import Union

if typing.TYPE_CHECKING:
from typing_extensions import TypeAlias

from .base import AWSPluginBase

ClientType = botocore.client.BaseClient
ResourceType = boto3.resources.base.ServiceResource
ClientType: TypeAlias = botocore.client.BaseClient
ResourceType: TypeAlias = boto3.resources.base.ServiceResource
BotoConn = Union[ClientType, ResourceType, Tuple[ClientType, ResourceType]]

from ansible.module_utils.basic import to_native
Expand Down