Skip to content

Commit

Permalink
Refactor ec2_transit_gateway_* modules (ansible-collections#2158)
Browse files Browse the repository at this point in the history
SUMMARY

Refactor ec2_transit_gateway and ec2_transit_gateway_info modules

common code moved to module_utils ansible-collections#2325
ISSUE TYPE

Bugfix Pull Request
Docs Pull Request
Feature Pull Request
New Module Pull Request

COMPONENT NAME

ec2_transit_gateway
ec2_transit_gateway_info
ADDITIONAL INFORMATION

Reviewed-by: GomathiselviS <[email protected]>
Reviewed-by: Alina Buzachis
Reviewed-by: Mandar Kulkarni <[email protected]>
Reviewed-by: Bikouo Aubin

This commit was initially merged in https://github.com/ansible-collections/community.aws
See: ansible-collections/community.aws@fc782d2
  • Loading branch information
mandar242 committed Oct 24, 2024
1 parent 49ddcbe commit 87029e9
Showing 1 changed file with 76 additions and 82 deletions.
158 changes: 76 additions & 82 deletions plugins/modules/ec2_transit_gateway_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,25 @@

DOCUMENTATION = r"""
module: ec2_transit_gateway_info
short_description: Gather information about ec2 transit gateways in AWS
short_description: Retrieve information about EC2 Transit Gateways in AWS
version_added: 1.0.0
description:
- Gather information about ec2 transit gateways in AWS
- Gather information about EC2 Transit Gateways in AWS.
author:
- "Bob Boldin (@BobBoldin)"
options:
transit_gateway_ids:
description:
- A list of transit gateway IDs to gather information for.
- A list of Transit Gateway IDs for which to gather information.
aliases: [transit_gateway_id]
type: list
elements: str
default: []
filters:
description:
- A dict of filters to apply. Each dict item consists of a filter key and a filter value.
See U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeTransitGateways.html) for filters.
- A dictionary of filters to apply to the query. Each key-value pair represents a filter key and its corresponding value.
- For a complete list of available filters,
refer to the AWS documentation U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeTransitGateways.html).
type: dict
default: {}
extends_documentation_fragment:
Expand Down Expand Up @@ -58,11 +59,12 @@

RETURN = r"""
transit_gateways:
description: >
Transit gateways that match the provided filters. Each element consists of a dict with all the information
related to that transit gateway.
description:
- Transit gateways that match the provided filters.
- Each element consists of a dict with all the information related to that transit gateway.
returned: on success
type: complex
type: list
elements: dict
contains:
creation_time:
description: The creation time.
Expand All @@ -77,65 +79,53 @@
options:
description: A dictionary of the transit gateway options.
returned: always
type: complex
type: dict
contains:
amazon_side_asn:
description:
- A private Autonomous System Number (ASN) for the Amazon
side of a BGP session. The range is 64512 to 65534 for
16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs.
- A private Autonomous System Number (ASN) for the Amazon ide of a BGP session.
- The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs.
returned: always
type: int
sample: 64512
auto_accept_shared_attachments:
description:
- Indicates whether attachment requests are automatically accepted.
description: Indicates whether attachment requests are automatically accepted.
returned: always
type: str
sample: "enable"
default_route_table_association:
description:
- Indicates whether resource attachments are automatically
associated with the default association route table.
description: Indicates whether resource attachments are automatically associated with the default association route table.
returned: always
type: str
sample: "disable"
association_default_route_table_id:
description:
- The ID of the default association route table.
description: The ID of the default association route table.
returned: when present
type: str
sample: "rtb-11223344"
sample: "tgw-rtb-0fd332c911223344"
default_route_table_propagation:
description:
- Indicates whether resource attachments automatically
propagate routes to the default propagation route table.
description: Indicates whether resource attachments automatically propagate routes to the default propagation route table.
returned: always
type: str
sample: "disable"
dns_support:
description:
- Indicates whether DNS support is enabled.
description: Indicates whether DNS support is enabled.
returned: always
type: str
sample: "enable"
multicast_support:
description:
- Indicates whether Multicast support is enabled.
description: Indicates whether Multicast support is enabled.
returned: always
type: str
sample: "enable"
version_added: 7.3.0
propagation_default_route_table_id:
description:
- The ID of the default propagation route table.
description: The ID of the default propagation route table.
returned: when present
type: str
sample: "rtb-11223344"
vpn_ecmp_support:
description:
- Indicates whether Equal Cost Multipath Protocol support
is enabled.
description: Indicates whether Equal Cost Multipath Protocol support is enabled.
returned: always
type: str
sample: "enable"
Expand All @@ -153,9 +143,10 @@
description: A dict of tags associated with the transit gateway.
returned: always
type: dict
sample: '{
"Name": "A sample TGW"
}'
sample: {
"Name": "A sample TGW",
"Env": "Dev"
}
transit_gateway_arn:
description: The Amazon Resource Name (ARN) of the transit gateway.
returned: always
Expand All @@ -168,67 +159,70 @@
sample: "tgw-02c42332e6b7da829"
"""

try:
import botocore
except ImportError:
pass # handled by imported AnsibleAWSModule
from typing import Any
from typing import Dict
from typing import List

from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict

from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_ec2_transit_gateways
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list

from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule


class AnsibleEc2TgwInfo(object):
def __init__(self, module, results):
self._module = module
self._results = results
self._connection = self._module.client("ec2")
self._check_mode = self._module.check_mode
def get_transit_gateway_response(module: AnsibleAWSModule, connection) -> Dict[str, Any]:
"""
Get transit gateway response from AWS.
@AWSRetry.exponential_backoff()
def describe_transit_gateways(self):
"""
Describe transit gateways.
module : AnsibleAWSModule object
connection : boto3 client connection object
:return: Response from describe_transit_gateways call
"""
filters = ansible_dict_to_boto3_filter_list(module.params["filters"])
transit_gateway_ids = module.params["transit_gateway_ids"]

module : AnsibleAWSModule object
connection : boto3 client connection object
"""
# collect parameters
filters = ansible_dict_to_boto3_filter_list(self._module.params["filters"])
transit_gateway_ids = self._module.params["transit_gateway_ids"]
params = {}
if transit_gateway_ids:
params["TransitGatewayIds"] = transit_gateway_ids
if filters:
params["Filters"] = filters

# init empty list for return vars
transit_gateway_info = list()
result = describe_ec2_transit_gateways(connection, **params)
return result

# Get the basic transit gateway info
try:
response = self._connection.describe_transit_gateways(
TransitGatewayIds=transit_gateway_ids, Filters=filters
)
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"]))
# convert tag list to ansible dict
transit_gateway_info[-1]["tags"] = boto3_tag_list_to_ansible_dict(transit_gateway.get("Tags", []))
def extract_transit_gateway_info(transit_gateway: Dict[str, Any]) -> Dict[str, Any]:
"""
Extract and transform transit gateway information.
self._results["transit_gateways"] = transit_gateway_info
return
transit_gateway : The transit gateway data from AWS
:return: Transformed transit gateway information
"""
tgw_data = camel_dict_to_snake_dict(transit_gateway, ignore_list=["Tags"])
tgw_data["tags"] = boto3_tag_list_to_ansible_dict(transit_gateway.get("Tags", []))
return tgw_data


def setup_module_object():
def describe_transit_gateways(module: AnsibleAWSModule, connection) -> List[Dict[str, Any]]:
"""
merge argument spec and create Ansible module object
:return: Ansible module object
Describe transit gateways.
module : AnsibleAWSModule object
connection : boto3 client connection object
:return: List of transit gateways
"""
response = get_transit_gateway_response(module, connection)
return [extract_transit_gateway_info(tgw) for tgw in response]


def setup_module_object() -> AnsibleAWSModule:
"""
Merge argument spec and create Ansible module object.
:return: Ansible module object
"""
argument_spec = dict(
transit_gateway_ids=dict(type="list", default=[], elements="str", aliases=["transit_gateway_id"]),
filters=dict(type="dict", default={}),
Expand All @@ -244,13 +238,13 @@ def setup_module_object():

def main():
module = setup_module_object()
results = {"changed": False}

results = dict(changed=False)

tgwf_manager = AnsibleEc2TgwInfo(module=module, results=results)
connection = module.client("ec2")
try:
tgwf_manager.describe_transit_gateways()
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
transit_gateways = describe_transit_gateways(module, connection)
results["transit_gateways"] = transit_gateways
except AnsibleEC2Error as e:
module.fail_json_aws(e)

module.exit_json(**results)
Expand Down

0 comments on commit 87029e9

Please sign in to comment.