def test__fail__key_error(self):
     """fail with key error"""
     tgw = TGWPeering()
     peer = TGWPeer(
         aws_region="",
         transit_gateway="",
         attachment_id="",
     )
     with pytest.raises(KeyError):
         tgw.delete_tgw_peering_attachment(peer)
    def test__success(self):
        """success"""
        tgw = TGWPeering()

        # mock setup
        attachment = tgw.ec2_client.create_transit_gateway_peering_attachment(
            TransitGatewayId="",
            PeerTransitGatewayId="",
            PeerAccountId="",
            PeerRegion="",
        )["TransitGatewayPeeringAttachment"]
        peer = TGWPeer(
            aws_region="",
            transit_gateway="",
            attachment_id=attachment["TransitGatewayAttachmentId"],
        )
        tgw.delete_tgw_peering_attachment(peer)
    def test__fail__client_error(self):
        """fail with client error"""

        tgw = TGWPeering()
        peer = TGWPeer(
            aws_region="",
            transit_gateway="",
            attachment_id="",
        )
        stubber = Stubber(tgw.ec2_client)
        _err_code = "InternalException"
        _message = "test error"
        stubber.add_client_error(
            "delete_transit_gateway_peering_attachment",
            service_error_code=_err_code,
            service_message=_message,
        )
        stubber.activate()
        with pytest.raises(ClientError) as err:
            tgw.delete_tgw_peering_attachment(peer)
        assert err.value.response["Error"]["Code"] == _err_code
        assert err.value.response["Error"]["Message"] == _message
        stubber.deactivate()
Beispiel #4
0
async def tag_event_router(tag_value: str) -> None:
    """Handles tag events for transit gateway

    Args:
        tag_value (str): tag value for the tgw tag-change event
    """
    logger.debug("handling tgw tag event")
    hub_tgw_id = environ.get("TGW_ID")
    tgw = TGWPeering()
    current_peers: list[TGWPeer] = tgw.get_tgw_peers(
        tgw_id=hub_tgw_id,
        states=[
            AttachmentState.AVAILABLE,
            AttachmentState.INITIATING,
            AttachmentState.INITIATING_REQUEST,
            AttachmentState.PENDING,
            AttachmentState.PENDING_ACCEPTANCE,
            AttachmentState.MODIFYING,
        ],
    )

    logger.debug("current tgw peers %s", current_peers)
    current_peer_tgw: list[str] = [i.transit_gateway for i in current_peers]

    # case of empty tag, delete all peering attachments
    if tag_value.upper() == "DELETE":
        for peer in current_peers:
            try:
                tgw.delete_tgw_peering_attachment(peer)
            except ClientError as err:
                logger.warning(str(err))
        return

    # for all other cases, create new and delete old peering attachments
    peer_list = tag_value.split("/")
    for peer in peer_list:
        peer = TGWPeer(transit_gateway=peer.split("_")[0],
                       aws_region=peer.split("_")[1])

        # creation of new peering attachments
        if peer.transit_gateway not in current_peer_tgw:
            try:
                tgw.create_tgw_peering_attachment(tgw_id=hub_tgw_id, peer=peer)
            except ClientError as err:
                logger.warning(str(err))
        else:
            current_peer_tgw.remove(peer.transit_gateway)

    # deleting old peering attachments
    for peer in current_peers:
        if peer.transit_gateway in current_peer_tgw:
            try:
                tgw.delete_tgw_peering_attachment(peer)
            except (KeyError, ClientError) as err:
                logger.warning(str(err))

    # accept all peering requests
    peering_requests: list[TGWPeer] = tgw.get_tgw_peers(
        tgw_id=hub_tgw_id,
        states=[
            AttachmentState.INITIATING,
            AttachmentState.INITIATING_REQUEST,
        ],
    )
    coros = [
        tgw.accept_tgw_peering_attachment(peer) for peer in peering_requests
    ]
    await asyncio.gather(*coros, return_exceptions=True)  # fail silently
    logger.info(
        "peering requests accepted, for failed requests turn debug mode and check logs"
    )