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
        sample_tgw1 = tgw.ec2_client.create_transit_gateway()
        peers = tgw.get_tgw_peers(
            tgw_id=sample_tgw1["TransitGateway"]["TransitGatewayId"],
            states=[AttachmentState.AVAILABLE],
        )
        assert len(peers) == 0
        # clean-up
        tgw.ec2_client.delete_transit_gateway(
            TransitGatewayId=sample_tgw1["TransitGateway"]["TransitGatewayId"])
 def test__fail__client_error(self):
     """fail with client error"""
     tgw = TGWPeering()
     stubber = Stubber(tgw.ec2_client)
     stubber.add_client_error(
         "describe_transit_gateway_peering_attachments",
         service_error_code="InternalException",
         service_message="this is test error",
     )
     stubber.activate()
     peers = tgw.get_tgw_peers(
         tgw_id="",
         states=[AttachmentState.AVAILABLE],
     )
     assert len(peers) == 0
     stubber.deactivate()
    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__success(self, mocker):
     """success"""
     tgw = TGWPeering()
     peer = TGWPeer(
         aws_region="",
         transit_gateway="",
         attachment_id="",
     )
     mocker.patch(
         "tgw_peering.lib.transit_gateway.TGWPeering.tgw_attachment_waiter",
         side_effect=WaiterError(
             name="TestWaiter",
             reason="error message",
             last_response="waiter_failed",
         ),
     )
     with pytest.raises(WaiterError) as err:
         asyncio.run(tgw.accept_tgw_peering_attachment(peer))
     assert str(err.value.last_response) == "waiter_failed"
    def test__fail__client_error(self):
        """fail with client error"""

        tgw = TGWPeering()
        stubber = Stubber(tgw.ec2_client)
        _err_code = "InternalException"
        _message = "test error"
        stubber.add_client_error(
            "create_transit_gateway_peering_attachment",
            service_error_code=_err_code,
            service_message=_message,
        )
        stubber.activate()
        peer = TGWPeer(transit_gateway="", aws_region="")
        with pytest.raises(ClientError) as err:
            tgw.create_tgw_peering_attachment(tgw_id="",
                                              peer=peer,
                                              peer_account_id="")
        assert err.value.response["Error"]["Code"] == _err_code
        assert err.value.response["Error"]["Message"] == _message
        stubber.deactivate()
    def test__success(self):
        """success"""
        tgw = TGWPeering()

        # mock setup
        sample_tgw1 = tgw.ec2_client.create_transit_gateway()
        sample_tgw2 = tgw.ec2_client.create_transit_gateway()
        sample_peer = TGWPeer(
            transit_gateway=sample_tgw2["TransitGateway"]["TransitGatewayId"],
            aws_region=environ.get("AWS_DEFAULT_REGION"),
        )
        attachment = tgw.create_tgw_peering_attachment(
            tgw_id=sample_tgw1["TransitGateway"]["TransitGatewayId"],
            peer=sample_peer,
            peer_account_id=self.owner,
        )

        sample_peer.attachment_id = attachment["TransitGatewayAttachmentId"]

        # test attachment is tagged with solution identifier
        assert attachment["Tags"][0]["Key"] == "SolutionId"
        assert attachment["Tags"][0]["Value"] == environ.get("SOLUTION_ID")

        peers = tgw.get_tgw_peers(
            tgw_id=sample_tgw1["TransitGateway"]["TransitGatewayId"],
            states=[AttachmentState.AVAILABLE],
        )

        assert isinstance(peers[0], TGWPeer)
        assert peers[0] == sample_peer

        # clean-up
        tgw.ec2_client.delete_transit_gateway_peering_attachment(
            TransitGatewayAttachmentId=attachment["TransitGatewayAttachmentId"]
        )
        tgw.ec2_client.delete_transit_gateway(
            TransitGatewayId=sample_tgw1["TransitGateway"]["TransitGatewayId"])
        tgw.ec2_client.delete_transit_gateway(
            TransitGatewayId=sample_tgw2["TransitGateway"]["TransitGatewayId"])
Ejemplo n.º 8
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"
    )