From 0ad2fae05fa12e08be48aa8eb8750ef13f7ffbaa Mon Sep 17 00:00:00 2001 From: Jun Lyu Date: Wed, 29 Oct 2025 17:37:08 -0700 Subject: [PATCH] fix: update get_execution_role to directly return the ExecutionRoleArn if it presents in the resource metadata file --- src/sagemaker/session.py | 8 ++++---- tests/unit/test_session.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/sagemaker/session.py b/src/sagemaker/session.py index 705d9892fe..13fd3155aa 100644 --- a/src/sagemaker/session.py +++ b/src/sagemaker/session.py @@ -6285,16 +6285,16 @@ def get_caller_identity_arn(self): user_profile_name = metadata.get("UserProfileName") execution_role_arn = metadata.get("ExecutionRoleArn") try: + # find execution role from the metadata file if present + if execution_role_arn is not None: + return execution_role_arn + if domain_id is None: instance_desc = self.sagemaker_client.describe_notebook_instance( NotebookInstanceName=instance_name ) return instance_desc["RoleArn"] - # find execution role from the metadata file if present - if execution_role_arn is not None: - return execution_role_arn - user_profile_desc = self.sagemaker_client.describe_user_profile( DomainId=domain_id, UserProfileName=user_profile_name ) diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index e3d763e612..721243096d 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -728,6 +728,25 @@ def test_get_caller_identity_arn_from_metadata_file_for_space(boto_session): assert actual == expected_role +@patch( + "six.moves.builtins.open", + mock_open( + read_data='{"ResourceName": "SageMakerInstance", ' + '"ExecutionRoleArn": "arn:aws:iam::369233609183:role/service-role/SageMakerRole-20171129T072388"}' + ), +) +@patch("os.path.exists", side_effect=mock_exists(NOTEBOOK_METADATA_FILE, True)) +def test_get_caller_identity_arn_from_metadata_file_with_no_domain_id(boto_session): + sess = Session(boto_session) + expected_role = "arn:aws:iam::369233609183:role/service-role/SageMakerRole-20171129T072388" + + actual = sess.get_caller_identity_arn() + + assert actual == expected_role + # Should not call describe_notebook_instance since ExecutionRoleArn is available + sess.sagemaker_client.describe_notebook_instance.assert_not_called() + + @patch( "six.moves.builtins.open", mock_open(read_data='{"ResourceName": "SageMakerInstance"}'),