You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "seanghaeli (via GitHub)" <gi...@apache.org> on 2026/05/11 23:19:02 UTC

[PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

seanghaeli opened a new pull request, #66736:
URL: https://github.com/apache/airflow/pull/66736

   ## Summary
   - Replace the fixed `time.sleep(60)` after IAM trust policy update with an active validation task that confirms propagation using exponential backoff
   - The new `wait_for_trust_policy_propagation` task uses `iam:GetRole` + `iam:SimulatePrincipalPolicy` to verify the trust policy is consistent before proceeding
   - Add `--retry 3 --retry-delay 5` to the eksctl curl download for transient network resilience
   
   ## Motivation
   The `example_emr_eks` system test was failing intermittently because IAM OIDC-based trust policy propagation can take 2-5+ minutes. The fixed sleep was either too short (causing auth failures) or unnecessarily long (wasting CI time).
   
   ## Test plan
   - [ ] Verify DAG parses without errors
   - [ ] Run system test end-to-end — confirm the validation task correctly detects propagation and proceeds
   - [ ] Confirm transient failure rate decreases over multiple runs
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes — Claude Code (Opus 4.6)
   
   Generated-by: Claude Code (Opus 4.6) following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas merged PR #66736:
URL: https://github.com/apache/airflow/pull/66736


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "seanghaeli (via GitHub)" <gi...@apache.org>.
seanghaeli commented on PR #66736:
URL: https://github.com/apache/airflow/pull/66736#issuecomment-4435114785

   Rebased cleanly — single commit now. Sorry about the mess earlier.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #66736:
URL: https://github.com/apache/airflow/pull/66736#issuecomment-4476419377

   @seanghaeli — There are 6 unresolved review thread(s) on this PR from @ferruzzi, @o-nikolas, @vincbeck. Could you either push a fix or reply in each thread explaining why the feedback doesn't apply? Once you believe the feedback is addressed, mark the thread as resolved so the reviewer isn't re-pinged needlessly. Thanks!
   
   ---
   
   _Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this [two-stage triage process](https://github.com/apache/airflow/blob/main/contributing-docs/25_maintainer_pr_triage.md#why-the-first-pass-is-automated) so that our maintainers' limited time is spent where it matters most: the conversation with you._
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #66736:
URL: https://github.com/apache/airflow/pull/66736#discussion_r3237046729


##########
providers/amazon/tests/system/amazon/aws/example_emr_eks.py:
##########
@@ -59,15 +60,13 @@
 JOB_ROLE_ARN_KEY = "JOB_ROLE_ARN"
 JOB_ROLE_NAME_KEY = "JOB_ROLE_NAME"
 SUBNETS_KEY = "SUBNETS"
-UPDATE_TRUST_POLICY_WAIT_TIME_KEY = "UPDATE_TRUST_POLICY_WAIT_TIME"
 
 sys_test_context_task = (
     SystemTestContextBuilder()
     .add_variable(ROLE_ARN_KEY)
     .add_variable(JOB_ROLE_ARN_KEY)
     .add_variable(JOB_ROLE_NAME_KEY)
     .add_variable(SUBNETS_KEY, split_string=True)
-    .add_variable(UPDATE_TRUST_POLICY_WAIT_TIME_KEY, optional=True, default_value="10")

Review Comment:
   Once merged, do not forget to remove this parameter from our internal configuration as well



##########
providers/amazon/tests/system/amazon/aws/example_emr_eks.py:
##########
@@ -177,8 +176,71 @@ def update_trust_policy_execution_role(cluster_name, cluster_namespace, role_nam
     if build.returncode != 0:
         raise RuntimeError(err)
 
-    # Wait for IAM changes to propagate to avoid authentication failures
-    time.sleep(int(wait_time))
+
+class TrustPolicyNotPropagatedError(Exception):
+    """Raised when the IAM trust policy has not yet propagated."""
+
+
+@task
+def wait_for_trust_policy_propagation(cluster_name, role_name):
+    """Validate that the IAM trust policy has propagated by checking the role's
+    trust policy contains the expected OIDC provider.
+
+    Uses exponential backoff retries (up to 5 minutes) instead of a fixed sleep,
+    which avoids both wasting time when propagation is fast and failing when it's slow.
+    """
+    log = logging.getLogger(__name__)
+
+    # Determine the expected OIDC provider ARN from the EKS cluster
+    eks_client = boto3.client("eks")
+    oidc_issuer_url = eks_client.describe_cluster(name=cluster_name)["cluster"]["identity"]["oidc"]["issuer"]
+    oidc_issuer_endpoint = oidc_issuer_url.replace("https://", "")
+    account_id = boto3.client("sts").get_caller_identity()["Account"]
+    expected_oidc_provider_arn = f"arn:aws:iam::{account_id}:oidc-provider/{oidc_issuer_endpoint}"
+
+    @retry(
+        retry=retry_if_exception_type(TrustPolicyNotPropagatedError),
+        wait=wait_exponential(multiplier=1, min=5, max=30),
+        stop=stop_after_delay(300),
+        reraise=True,
+    )
+    def _validate_trust_policy():
+        iam_client = boto3.client("iam")
+
+        # Step 1: Verify the trust policy document contains the expected OIDC provider
+        role = iam_client.get_role(RoleName=role_name)["Role"]
+        trust_policy = role["AssumeRolePolicyDocument"]
+
+        has_oidc_statement = False
+        for statement in trust_policy.get("Statement", []):
+            if statement.get("Action") != "sts:AssumeRoleWithWebIdentity":
+                continue
+            principal = statement.get("Principal", {})
+            federated = principal.get("Federated", "")
+            if oidc_issuer_endpoint in federated:
+                has_oidc_statement = True
+                break
+
+        if not has_oidc_statement:
+            log.info(
+                "Trust policy does not yet contain OIDC provider %s, retrying...",
+                expected_oidc_provider_arn,
+            )
+            raise TrustPolicyNotPropagatedError(
+                f"Trust policy for role {role_name} does not yet contain "
+                f"the expected OIDC provider: {expected_oidc_provider_arn}"
+            )
+
+        log.info("Trust policy document confirmed for role %s", role_name)
+
+    _validate_trust_policy()
+
+    # Brief buffer after IAM confirms the trust policy document — cross-service
+    # caches (EKS/EMR) may still serve the old policy for a few seconds.
+    import time
+
+    time.sleep(15)

Review Comment:
   No longer needed then?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #66736:
URL: https://github.com/apache/airflow/pull/66736#issuecomment-4431360889

   Bad rebase


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #66736:
URL: https://github.com/apache/airflow/pull/66736#discussion_r3236527205


##########
providers/amazon/tests/system/amazon/aws/example_emr_eks.py:
##########
@@ -177,8 +176,71 @@ def update_trust_policy_execution_role(cluster_name, cluster_namespace, role_nam
     if build.returncode != 0:
         raise RuntimeError(err)
 
-    # Wait for IAM changes to propagate to avoid authentication failures
-    time.sleep(int(wait_time))
+
+class TrustPolicyNotPropagatedError(Exception):
+    """Raised when the IAM trust policy has not yet propagated."""
+
+
+@task
+def wait_for_trust_policy_propagation(cluster_name, role_name):
+    """Validate that the IAM trust policy has propagated by checking the role's
+    trust policy contains the expected OIDC provider.
+
+    Uses exponential backoff retries (up to 5 minutes) instead of a fixed sleep,
+    which avoids both wasting time when propagation is fast and failing when it's slow.
+    """
+    log = logging.getLogger(__name__)
+
+    # Determine the expected OIDC provider ARN from the EKS cluster
+    eks_client = boto3.client("eks")
+    oidc_issuer_url = eks_client.describe_cluster(name=cluster_name)["cluster"]["identity"]["oidc"]["issuer"]
+    oidc_issuer_endpoint = oidc_issuer_url.replace("https://", "")
+    account_id = boto3.client("sts").get_caller_identity()["Account"]
+    expected_oidc_provider_arn = f"arn:aws:iam::{account_id}:oidc-provider/{oidc_issuer_endpoint}"
+
+    @retry(
+        retry=retry_if_exception_type(TrustPolicyNotPropagatedError),
+        wait=wait_exponential(multiplier=1, min=5, max=30),
+        stop=stop_after_delay(300),
+        reraise=True,
+    )
+    def _validate_trust_policy():
+        iam_client = boto3.client("iam")
+
+        # Step 1: Verify the trust policy document contains the expected OIDC provider
+        role = iam_client.get_role(RoleName=role_name)["Role"]
+        trust_policy = role["AssumeRolePolicyDocument"]
+
+        has_oidc_statement = False
+        for statement in trust_policy.get("Statement", []):
+            if statement.get("Action") != "sts:AssumeRoleWithWebIdentity":
+                continue
+            principal = statement.get("Principal", {})
+            federated = principal.get("Federated", "")
+            if oidc_issuer_endpoint in federated:
+                has_oidc_statement = True
+                break
+
+        if not has_oidc_statement:
+            log.info(
+                "Trust policy does not yet contain OIDC provider %s, retrying...",
+                expected_oidc_provider_arn,
+            )
+            raise TrustPolicyNotPropagatedError(
+                f"Trust policy for role {role_name} does not yet contain "
+                f"the expected OIDC provider: {expected_oidc_provider_arn}"
+            )
+
+        log.info("Trust policy document confirmed for role %s", role_name)
+
+    _validate_trust_policy()
+
+    # Brief buffer after IAM confirms the trust policy document — cross-service
+    # caches (EKS/EMR) may still serve the old policy for a few seconds.
+    import time

Review Comment:
   Move the import back to the top??



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #66736:
URL: https://github.com/apache/airflow/pull/66736#discussion_r3222755688


##########
airflow-core/src/airflow/utils/log/callback_log_reader.py:
##########
@@ -0,0 +1,146 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Reader for callback execution logs stored in remote or local storage."""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections.abc import Generator
+from contextlib import suppress
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from airflow.configuration import conf
+from airflow.utils.log.file_task_handler import (
+    StructuredLogMessage,
+    _interleave_logs,
+    _stream_lines_by_chunk,
+)
+
+if TYPE_CHECKING:
+    from airflow._shared.logging.remote import LogSourceInfo, RawLogStream
+
+logger = logging.getLogger(__name__)
+
+
+def _get_callback_log_relative_path(dag_id: str, run_id: str, callback_id: str) -> str:
+    """
+    Construct the relative log path for a callback execution.
+
+    This must match the path format used in ExecuteCallback.make():
+        executor_callbacks/{dag_id}/{run_id}/{callback_id}
+    """
+    return f"executor_callbacks/{dag_id}/{run_id}/{callback_id}"
+
+
+def read_callback_log(
+    dag_id: str,
+    run_id: str,
+    callback_id: str,
+) -> Generator[StructuredLogMessage, None, None]:
+    """
+    Read callback logs from remote and/or local storage.
+
+    Tries remote storage first (if configured), then falls back to local filesystem.
+    Returns a generator of StructuredLogMessage objects suitable for the API response.
+
+    :param dag_id: The Dag ID associated with the callback.
+    :param run_id: The Dag run ID associated with the callback.
+    :param callback_id: The unique callback identifier.
+    :return: Generator of StructuredLogMessage objects.
+    """
+    relative_path = _get_callback_log_relative_path(dag_id, run_id, callback_id)
+
+    sources: LogSourceInfo = []
+    remote_logs: list[RawLogStream] = []
+    local_logs: list[RawLogStream] = []
+
+    # Try remote storage first
+    with suppress(Exception):
+        remote_sources, remote_log_streams = _read_callback_remote_logs(relative_path)
+        if remote_log_streams:
+            sources.extend(remote_sources)
+            remote_logs.extend(remote_log_streams)
+
+    # Try local filesystem
+    if not remote_logs:
+        local_sources, local_log_streams = _read_callback_local_logs(relative_path)
+        if local_log_streams:
+            sources.extend(local_sources)
+            local_logs.extend(local_log_streams)
+
+    if not remote_logs and not local_logs:
+        yield StructuredLogMessage(event="No callback logs found.", timestamp=None)
+        return
+
+    # Emit source information header
+    yield StructuredLogMessage(event="::group::Log message source details", sources=sources)  # type: ignore[call-arg]
+    yield StructuredLogMessage(event="::endgroup::")
+
+    # Interleave and yield all log streams
+    log_stream = _interleave_logs(*remote_logs, *local_logs)
+    yield from log_stream
+
+
+def _read_callback_remote_logs(
+    relative_path: str,
+) -> tuple[list[str], list[RawLogStream]]:
+    """Read callback logs from the configured remote log storage."""
+    from airflow.logging_config import get_remote_task_log
+
+    remote_io = get_remote_task_log()
+    if remote_io is None:
+        return [], []
+
+    # RemoteLogIO.read() takes (relative_path, ti) -- for S3 the ti is not used,
+    # for CloudWatch it uses ti.end_date (with getattr fallback to None).
+    # We pass None since callbacks don't have a TaskInstance.
+    if stream_method := getattr(remote_io, "stream", None):
+        sources, logs = stream_method(relative_path, None)
+        return sources, logs or []
+
+    sources, logs = remote_io.read(relative_path, None)  # type: ignore[arg-type]
+    if not logs:
+        return sources, []
+
+    # Convert legacy string logs to stream format
+    from airflow.utils.log.file_task_handler import _get_compatible_log_stream
+
+    return sources, [_get_compatible_log_stream(logs)]
+
+
+def _read_callback_local_logs(
+    relative_path: str,
+) -> tuple[list[str], list[RawLogStream]]:
+    """Read callback logs from the local filesystem."""
+    base_log_folder = conf.get("logging", "base_log_folder")
+    log_path = Path(base_log_folder) / relative_path
+
+    sources: list[str] = []
+    log_streams: list[RawLogStream] = []
+
+    # Look for log files matching the path pattern (similar to FileTaskHandler._read_from_local)
+    paths = sorted(log_path.parent.glob(log_path.name + "*"))

Review Comment:
   ## CodeQL / Uncontrolled data used in path expression
   
   This path depends on a [user-provided value](1).
   This path depends on a [user-provided value](2).
   This path depends on a [user-provided value](3).
   
   [Show more details](https://github.com/apache/airflow/security/code-scanning/599)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "seanghaeli (via GitHub)" <gi...@apache.org>.
seanghaeli commented on code in PR #66736:
URL: https://github.com/apache/airflow/pull/66736#discussion_r3270218425


##########
providers/amazon/tests/system/amazon/aws/example_emr_eks.py:
##########
@@ -177,8 +176,71 @@ def update_trust_policy_execution_role(cluster_name, cluster_namespace, role_nam
     if build.returncode != 0:
         raise RuntimeError(err)
 
-    # Wait for IAM changes to propagate to avoid authentication failures
-    time.sleep(int(wait_time))
+
+class TrustPolicyNotPropagatedError(Exception):
+    """Raised when the IAM trust policy has not yet propagated."""
+
+
+@task
+def wait_for_trust_policy_propagation(cluster_name, role_name):
+    """Validate that the IAM trust policy has propagated by checking the role's
+    trust policy contains the expected OIDC provider.
+
+    Uses exponential backoff retries (up to 5 minutes) instead of a fixed sleep,
+    which avoids both wasting time when propagation is fast and failing when it's slow.
+    """
+    log = logging.getLogger(__name__)
+
+    # Determine the expected OIDC provider ARN from the EKS cluster
+    eks_client = boto3.client("eks")
+    oidc_issuer_url = eks_client.describe_cluster(name=cluster_name)["cluster"]["identity"]["oidc"]["issuer"]
+    oidc_issuer_endpoint = oidc_issuer_url.replace("https://", "")
+    account_id = boto3.client("sts").get_caller_identity()["Account"]
+    expected_oidc_provider_arn = f"arn:aws:iam::{account_id}:oidc-provider/{oidc_issuer_endpoint}"
+
+    @retry(
+        retry=retry_if_exception_type(TrustPolicyNotPropagatedError),
+        wait=wait_exponential(multiplier=1, min=5, max=30),
+        stop=stop_after_delay(300),
+        reraise=True,
+    )
+    def _validate_trust_policy():
+        iam_client = boto3.client("iam")
+
+        # Step 1: Verify the trust policy document contains the expected OIDC provider
+        role = iam_client.get_role(RoleName=role_name)["Role"]
+        trust_policy = role["AssumeRolePolicyDocument"]
+
+        has_oidc_statement = False
+        for statement in trust_policy.get("Statement", []):
+            if statement.get("Action") != "sts:AssumeRoleWithWebIdentity":
+                continue
+            principal = statement.get("Principal", {})
+            federated = principal.get("Federated", "")
+            if oidc_issuer_endpoint in federated:
+                has_oidc_statement = True
+                break
+
+        if not has_oidc_statement:
+            log.info(
+                "Trust policy does not yet contain OIDC provider %s, retrying...",
+                expected_oidc_provider_arn,
+            )
+            raise TrustPolicyNotPropagatedError(
+                f"Trust policy for role {role_name} does not yet contain "
+                f"the expected OIDC provider: {expected_oidc_provider_arn}"
+            )
+
+        log.info("Trust policy document confirmed for role %s", role_name)
+
+    _validate_trust_policy()
+
+    # Brief buffer after IAM confirms the trust policy document — cross-service
+    # caches (EKS/EMR) may still serve the old policy for a few seconds.
+    import time
+
+    time.sleep(15)

Review Comment:
   I think it's worth leaving as a safety buffer. Giving some time for the caches to update so the stale policy is not served



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Replace fixed sleep with IAM trust policy validation in example_emr_eks [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #66736:
URL: https://github.com/apache/airflow/pull/66736#discussion_r3245064194


##########
providers/amazon/tests/system/amazon/aws/example_emr_eks.py:
##########
@@ -177,8 +176,71 @@ def update_trust_policy_execution_role(cluster_name, cluster_namespace, role_nam
     if build.returncode != 0:
         raise RuntimeError(err)
 
-    # Wait for IAM changes to propagate to avoid authentication failures
-    time.sleep(int(wait_time))
+
+class TrustPolicyNotPropagatedError(Exception):
+    """Raised when the IAM trust policy has not yet propagated."""
+
+
+@task
+def wait_for_trust_policy_propagation(cluster_name, role_name):
+    """Validate that the IAM trust policy has propagated by checking the role's
+    trust policy contains the expected OIDC provider.
+
+    Uses exponential backoff retries (up to 5 minutes) instead of a fixed sleep,
+    which avoids both wasting time when propagation is fast and failing when it's slow.
+    """
+    log = logging.getLogger(__name__)
+
+    # Determine the expected OIDC provider ARN from the EKS cluster
+    eks_client = boto3.client("eks")
+    oidc_issuer_url = eks_client.describe_cluster(name=cluster_name)["cluster"]["identity"]["oidc"]["issuer"]
+    oidc_issuer_endpoint = oidc_issuer_url.replace("https://", "")
+    account_id = boto3.client("sts").get_caller_identity()["Account"]
+    expected_oidc_provider_arn = f"arn:aws:iam::{account_id}:oidc-provider/{oidc_issuer_endpoint}"
+
+    @retry(
+        retry=retry_if_exception_type(TrustPolicyNotPropagatedError),

Review Comment:
   We could probably just catch RuntimeError or another built in. This seems a bit overkill. Most of the stuff that will throw below are ClientErrors and index errors



##########
providers/amazon/tests/system/amazon/aws/example_emr_eks.py:
##########
@@ -177,8 +176,71 @@ def update_trust_policy_execution_role(cluster_name, cluster_namespace, role_nam
     if build.returncode != 0:
         raise RuntimeError(err)
 
-    # Wait for IAM changes to propagate to avoid authentication failures
-    time.sleep(int(wait_time))
+
+class TrustPolicyNotPropagatedError(Exception):
+    """Raised when the IAM trust policy has not yet propagated."""
+
+
+@task
+def wait_for_trust_policy_propagation(cluster_name, role_name):
+    """Validate that the IAM trust policy has propagated by checking the role's
+    trust policy contains the expected OIDC provider.
+
+    Uses exponential backoff retries (up to 5 minutes) instead of a fixed sleep,
+    which avoids both wasting time when propagation is fast and failing when it's slow.
+    """
+    log = logging.getLogger(__name__)
+
+    # Determine the expected OIDC provider ARN from the EKS cluster
+    eks_client = boto3.client("eks")
+    oidc_issuer_url = eks_client.describe_cluster(name=cluster_name)["cluster"]["identity"]["oidc"]["issuer"]
+    oidc_issuer_endpoint = oidc_issuer_url.replace("https://", "")
+    account_id = boto3.client("sts").get_caller_identity()["Account"]
+    expected_oidc_provider_arn = f"arn:aws:iam::{account_id}:oidc-provider/{oidc_issuer_endpoint}"
+
+    @retry(
+        retry=retry_if_exception_type(TrustPolicyNotPropagatedError),
+        wait=wait_exponential(multiplier=1, min=5, max=30),
+        stop=stop_after_delay(300),
+        reraise=True,
+    )
+    def _validate_trust_policy():
+        iam_client = boto3.client("iam")
+
+        # Step 1: Verify the trust policy document contains the expected OIDC provider

Review Comment:
   If there's just one Step you can remove that bit



##########
providers/amazon/tests/system/amazon/aws/example_emr_eks.py:
##########
@@ -110,7 +109,7 @@ def run_eksctl_commands(cluster_name, ns):
     # See https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/setting-up-cluster-access.html
     file = "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz"
     commands = f"""
-        curl --silent --location "{file}" | tar xz -C /tmp &&
+        curl --silent --location --retry 3 --retry-delay 5 "{file}" | tar xz -C /tmp &&

Review Comment:
   Doesn't this separate `--location` flag from the `"{file}"` value? Also why are we adding the retry and retry-delay here? Isn't the problem solved by your new wait task below?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org