Skip to content

change: create role if needed in get_execution_role #4323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions src/sagemaker/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -6902,13 +6902,16 @@ def production_variant(
return production_variant_configuration


def get_execution_role(sagemaker_session=None):
def get_execution_role(sagemaker_session=None, use_default=False):
"""Return the role ARN whose credentials are used to call the API.

Throws an exception if role doesn't exist.

Args:
sagemaker_session(Session): Current sagemaker session
sagemaker_session (Session): Current sagemaker session.
use_default (bool): Use a default role if ``get_caller_identity_arn`` does not
return a correct role. This default role will be created if needed.
Defaults to ``False``.

Returns:
(str): The role ARN
Expand All @@ -6919,6 +6922,41 @@ def get_execution_role(sagemaker_session=None):

if ":role/" in arn:
return arn

if use_default:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check if the default role already exists before creating. if so, then use that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did that in the try except block below

default_role_name = "AmazonSageMaker-DefaultRole"

LOGGER.warning("Using default role: %s", default_role_name)

boto3_session = sagemaker_session.boto_session
permissions_policy = json.dumps(
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": ["sagemaker.amazonaws.com"]},
"Action": "sts:AssumeRole",
}
],
}
)
iam_client = boto3_session.client("iam")
try:
iam_client.get_role(RoleName=default_role_name)
except iam_client.exceptions.NoSuchEntityException:
iam_client.create_role(
RoleName=default_role_name, AssumeRolePolicyDocument=str(permissions_policy)
)

LOGGER.warning("Created new sagemaker execution role: %s", default_role_name)

iam_client.attach_role_policy(
PolicyArn="arn:aws:iam::aws:policy/AmazonSageMakerFullAccess",
RoleName=default_role_name,
)
return iam_client.get_role(RoleName=default_role_name)["Role"]["Arn"]

message = (
"The current AWS identity is not a role: {}, therefore it cannot be used as a "
"SageMaker execution role"
Expand Down
62 changes: 62 additions & 0 deletions tests/unit/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import copy
import datetime
import io
import json
import logging
import os

Expand Down Expand Up @@ -532,6 +533,67 @@ def test_get_execution_role_throws_exception_if_arn_is_not_role_with_role_in_nam
assert "The current AWS identity is not a role" in str(error.value)


def test_get_execution_role_get_default_role(caplog):
session = Mock()
session.get_caller_identity_arn.return_value = "arn:aws:iam::369233609183:user/marcos"

iam_client = Mock()
iam_client.get_role.return_value = {"Role": {"Arn": "foo-role"}}
boto_session = Mock()
boto_session.client.return_value = iam_client

session.boto_session = boto_session
actual = get_execution_role(session, use_default=True)

iam_client.get_role.assert_called_with(RoleName="AmazonSageMaker-DefaultRole")
iam_client.attach_role_policy.assert_called_with(
PolicyArn="arn:aws:iam::aws:policy/AmazonSageMakerFullAccess",
RoleName="AmazonSageMaker-DefaultRole",
)
assert "Using default role: AmazonSageMaker-DefaultRole" in caplog.text
assert actual == "foo-role"


def test_get_execution_role_create_default_role(caplog):
session = Mock()
session.get_caller_identity_arn.return_value = "arn:aws:iam::369233609183:user/marcos"
permissions_policy = json.dumps(
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": ["sagemaker.amazonaws.com"]},
"Action": "sts:AssumeRole",
}
],
}
)
iam_client = Mock()
iam_client.exceptions.NoSuchEntityException = Exception
iam_client.get_role = Mock(side_effect=[Exception(), {"Role": {"Arn": "foo-role"}}])

boto_session = Mock()
boto_session.client.return_value = iam_client

session.boto_session = boto_session

actual = get_execution_role(session, use_default=True)

iam_client.create_role.assert_called_with(
RoleName="AmazonSageMaker-DefaultRole", AssumeRolePolicyDocument=str(permissions_policy)
)

iam_client.attach_role_policy.assert_called_with(
PolicyArn="arn:aws:iam::aws:policy/AmazonSageMakerFullAccess",
RoleName="AmazonSageMaker-DefaultRole",
)

assert "Created new sagemaker execution role: AmazonSageMaker-DefaultRole" in caplog.text

assert actual == "foo-role"


@patch(
"six.moves.builtins.open",
mock_open(read_data='{"ResourceName": "SageMakerInstance"}'),
Expand Down