This is an automated email from the ASF dual-hosted git repository.

vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new 9d13d24461a Retry EKS Fargate profile creation while the cluster has 
an update in progress (#77505)
9d13d24461a is described below

commit 9d13d24461ad52bc1d26d4749498047dae72c1dc
Author: Vincent <[email protected]>
AuthorDate: Tue Nov 24 15:08:39 2026 -0500

    Retry EKS Fargate profile creation while the cluster has an update in 
progress (#77505)
    
    A cluster that just turned ACTIVE can still reject CreateFargateProfile with
    ResourceInUseException ("cluster ... currently has an update in progress").
    DescribeCluster does not expose that update, so it cannot be waited on.
    Retry the call with the same backoff the delete operators already use.
    
    CreateFargateProfile also raises ResourceInUseException when a profile with
    the same name already exists. Only the "update in progress" case is retried,
    so a duplicate name still fails right away.
---
 .../airflow/providers/amazon/aws/operators/eks.py  | 22 +++++++---
 .../airflow/providers/amazon/aws/utils/__init__.py | 30 +++++++++++--
 .../tests/unit/amazon/aws/operators/test_eks.py    | 24 ++++++++++
 .../tests/unit/amazon/aws/utils/test_utils.py      | 51 ++++++++++++++++++++++
 4 files changed, 116 insertions(+), 11 deletions(-)

diff --git a/providers/amazon/src/airflow/providers/amazon/aws/operators/eks.py 
b/providers/amazon/src/airflow/providers/amazon/aws/operators/eks.py
index 63c450b8490..d31f7f19194 100644
--- a/providers/amazon/src/airflow/providers/amazon/aws/operators/eks.py
+++ b/providers/amazon/src/airflow/providers/amazon/aws/operators/eks.py
@@ -45,6 +45,7 @@ from airflow.providers.amazon.aws.triggers.eks import (
 )
 from airflow.providers.amazon.aws.utils import (
     build_resource_in_use_retry_args,
+    is_update_in_progress_error,
     validate_execute_complete_event,
 )
 from airflow.providers.amazon.aws.utils.deferral import should_defer
@@ -192,13 +193,20 @@ def _create_compute(
                 )
             )
 
-        eks_hook.create_fargate_profile(
-            clusterName=cluster_name,
-            fargateProfileName=fargate_profile_name,
-            podExecutionRoleArn=fargate_pod_execution_role_arn,
-            selectors=fargate_selectors,
-            **create_fargate_profile_kwargs,
-        )
+        # A cluster that just turned ACTIVE can still reject 
CreateFargateProfile because it "currently
+        # has an update in progress". DescribeCluster does not expose that 
update, so it cannot be
+        # waited on; retry the call instead.
+        for attempt in tenacity.Retrying(
+            **build_resource_in_use_retry_args(log, 
predicate=is_update_in_progress_error)
+        ):
+            with attempt:
+                eks_hook.create_fargate_profile(
+                    clusterName=cluster_name,
+                    fargateProfileName=fargate_profile_name,
+                    podExecutionRoleArn=fargate_pod_execution_role_arn,
+                    selectors=fargate_selectors,
+                    **create_fargate_profile_kwargs,
+                )
         if wait_for_completion:
             log.info("Waiting for Fargate profile to provision.  This will 
take some time.")
             wait(
diff --git 
a/providers/amazon/src/airflow/providers/amazon/aws/utils/__init__.py 
b/providers/amazon/src/airflow/providers/amazon/aws/utils/__init__.py
index 36b43290fef..d5982f146eb 100644
--- a/providers/amazon/src/airflow/providers/amazon/aws/utils/__init__.py
+++ b/providers/amazon/src/airflow/providers/amazon/aws/utils/__init__.py
@@ -32,12 +32,15 @@ from airflow.utils.helpers import prune_dict
 from airflow.version import version
 
 if TYPE_CHECKING:
+    from collections.abc import Callable
+
     from airflow.sdk.types import Logger
 
 log = logging.getLogger(__name__)
 
-# AWS rejects a delete call with ResourceInUseException while the target 
resource is still settling
-# from a prior operation (e.g. EKS finalizing a nodegroup removal before the 
cluster can be deleted).
+# AWS rejects a call with ResourceInUseException while the target resource is 
still settling from a
+# prior operation (e.g. EKS finalizing a nodegroup removal before the cluster 
can be deleted, or a
+# freshly ACTIVE cluster still finishing an internal update when a Fargate 
profile is created).
 # Retry with exponential backoff (1s, 2s, 4s, ... capped at 
RESOURCE_IN_USE_RETRY_MAX_WAIT per wait)
 # until RESOURCE_IN_USE_RETRY_TIMEOUT elapses, then give up and re-raise. The 
window has to cover an
 # EKS cluster reporting "an update in progress" for over ten minutes after a 
Fargate profile became
@@ -54,7 +57,24 @@ def is_resource_in_use_error(exception: BaseException) -> 
bool:
     )
 
 
-def build_resource_in_use_retry_args(logger: Logger | logging.Logger) -> 
dict[str, Any]:
+def is_update_in_progress_error(exception: BaseException) -> bool:
+    """
+    Return True if the exception is a ``ResourceInUseException`` caused by an 
update in progress.
+
+    Create calls also raise ``ResourceInUseException`` when a resource with 
the same name already
+    exists, which no amount of retrying fixes. Matching the message keeps that 
case failing fast.
+    """
+    return (
+        isinstance(exception, ClientError)
+        and exception.response.get("Error", {}).get("Code") == 
"ResourceInUseException"
+        and "update in progress" in exception.response.get("Error", 
{}).get("Message", "").lower()
+    )
+
+
+def build_resource_in_use_retry_args(
+    logger: Logger | logging.Logger,
+    predicate: Callable[[BaseException], bool] = is_resource_in_use_error,
+) -> dict[str, Any]:
     """
     Build tenacity arguments for retrying a call on a transient 
``ResourceInUseException``.
 
@@ -62,9 +82,11 @@ def build_resource_in_use_retry_args(logger: Logger | 
logging.Logger) -> dict[st
     (``tenacity.AsyncRetrying``) so both back off identically. 
``reraise=True`` keeps the
     original error as the task failure once the retry timeout is exhausted. 
Accepts either an
     Airflow structlog logger (``self.log``) or a stdlib ``logging.Logger`` 
(module-level helpers).
+    ``predicate`` decides which exceptions are retried; pass 
``is_update_in_progress_error`` for
+    create calls, where ``ResourceInUseException`` can also mean the resource 
already exists.
     """
     return {
-        "retry": tenacity.retry_if_exception(is_resource_in_use_error),
+        "retry": tenacity.retry_if_exception(predicate),
         "wait": tenacity.wait_exponential(max=RESOURCE_IN_USE_RETRY_MAX_WAIT),
         "stop": tenacity.stop_after_delay(RESOURCE_IN_USE_RETRY_TIMEOUT),
         "before_sleep": tenacity.before_sleep_log(logger, logging.WARNING),
diff --git a/providers/amazon/tests/unit/amazon/aws/operators/test_eks.py 
b/providers/amazon/tests/unit/amazon/aws/operators/test_eks.py
index e76eb351f4c..02c6da4ec5b 100644
--- a/providers/amazon/tests/unit/amazon/aws/operators/test_eks.py
+++ b/providers/amazon/tests/unit/amazon/aws/operators/test_eks.py
@@ -520,6 +520,30 @@ class TestEksCreateFargateProfileOperator:
             "Trigger is not a EksCreateFargateProfileTrigger"
         )
 
+    @mock.patch("time.sleep", return_value=None)
+    @mock.patch.object(EksHook, "create_fargate_profile")
+    def test_create_fargate_profile_retries_only_on_cluster_update_in_progress(
+        self, mock_create_fargate_profile, mock_sleep
+    ):
+        already_exists = ClientError(
+            error_response={
+                "Error": {
+                    "Code": "ResourceInUseException",
+                    "Message": "A Fargate Profile already exists with this 
name in this cluster.",
+                }
+            },
+            operation_name="CreateFargateProfile",
+        )
+        mock_create_fargate_profile.side_effect = [RESOURCE_IN_USE_ERROR, 
already_exists]
+        operator = EksCreateFargateProfileOperator(task_id=TASK_ID, 
**self.create_fargate_profile_params)
+
+        with pytest.raises(ClientError) as exc_info:
+            operator.execute({})
+
+        assert exc_info.value is already_exists
+        assert mock_create_fargate_profile.call_count == 2
+        
mock_create_fargate_profile.assert_called_with(**convert_keys(self.create_fargate_profile_params))
+
     def test_template_fields(self):
         op = EksCreateFargateProfileOperator(task_id=TASK_ID, 
**self.create_fargate_profile_params)
 
diff --git a/providers/amazon/tests/unit/amazon/aws/utils/test_utils.py 
b/providers/amazon/tests/unit/amazon/aws/utils/test_utils.py
index 3e7bb087919..83059b3718d 100644
--- a/providers/amazon/tests/unit/amazon/aws/utils/test_utils.py
+++ b/providers/amazon/tests/unit/amazon/aws/utils/test_utils.py
@@ -33,6 +33,7 @@ from airflow.providers.amazon.aws.utils import (
     get_airflow_version,
     get_botocore_version,
     is_resource_in_use_error,
+    is_update_in_progress_error,
 )
 
 DT = datetime.datetime(2000, 1, 1, tzinfo=datetime.UTC)
@@ -132,3 +133,53 @@ def 
test_build_resource_in_use_retry_args_does_not_retry_other_errors(mock_sleep
         _run_with_retry(call)
 
     assert call.call_count == 1
+
+
[email protected](
+    ("exception", "expected"),
+    [
+        pytest.param(
+            ClientError(
+                {
+                    "Error": {
+                        "Code": "ResourceInUseException",
+                        "Message": "Cannot create Fargate Profile p because 
cluster c currently has an "
+                        "update in progress",
+                    }
+                },
+                "CreateFargateProfile",
+            ),
+            True,
+            id="update_in_progress",
+        ),
+        pytest.param(
+            ClientError(
+                {
+                    "Error": {
+                        "Code": "ResourceInUseException",
+                        "Message": "A Fargate Profile already exists with this 
name in this cluster.",
+                    }
+                },
+                "CreateFargateProfile",
+            ),
+            False,
+            id="already_exists",
+        ),
+        pytest.param(
+            ClientError({"Error": {"Code": "ResourceInUseException"}}, 
"CreateFargateProfile"),
+            False,
+            id="no_message",
+        ),
+        pytest.param(
+            ClientError(
+                {"Error": {"Code": "InvalidRequestException", "Message": 
"update in progress"}},
+                "CreateFargateProfile",
+            ),
+            False,
+            id="other_client_error",
+        ),
+        pytest.param(ValueError("update in progress"), False, 
id="non_client_error"),
+    ],
+)
+def test_is_update_in_progress_error(exception, expected):
+    assert is_update_in_progress_error(exception) is expected

Reply via email to