Skip to content

Commit 0b25a89

Browse files
trungleducakrishna1995
authored andcommitted
Create role if needed in get_execution_role
1 parent a031739 commit 0b25a89

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

src/sagemaker/session.py

+40-2
Original file line numberDiff line numberDiff line change
@@ -6902,13 +6902,16 @@ def production_variant(
69026902
return production_variant_configuration
69036903

69046904

6905-
def get_execution_role(sagemaker_session=None):
6905+
def get_execution_role(sagemaker_session=None, use_default=False):
69066906
"""Return the role ARN whose credentials are used to call the API.
69076907
69086908
Throws an exception if role doesn't exist.
69096909
69106910
Args:
6911-
sagemaker_session(Session): Current sagemaker session
6911+
sagemaker_session(Session): Current sagemaker session.
6912+
use_default(bool): Use a default role if `get_caller_identity_arn does not
6913+
return a correct role. This default role will be created if needed.
6914+
Defaults to ``False``.
69126915
69136916
Returns:
69146917
(str): The role ARN
@@ -6919,6 +6922,41 @@ def get_execution_role(sagemaker_session=None):
69196922

69206923
if ":role/" in arn:
69216924
return arn
6925+
6926+
if use_default:
6927+
default_role_name = "AmazonSageMaker-DefaultRole"
6928+
6929+
LOGGER.warning("Using default role: %s", default_role_name)
6930+
6931+
boto3_session = sagemaker_session.boto_session
6932+
permissions_policy = json.dumps(
6933+
{
6934+
"Version": "2012-10-17",
6935+
"Statement": [
6936+
{
6937+
"Effect": "Allow",
6938+
"Principal": {"Service": ["sagemaker.amazonaws.com"]},
6939+
"Action": "sts:AssumeRole",
6940+
}
6941+
],
6942+
}
6943+
)
6944+
iam_client = boto3_session.client("iam")
6945+
try:
6946+
iam_client.get_role(RoleName=default_role_name)
6947+
except iam_client.exceptions.NoSuchEntityException:
6948+
iam_client.create_role(
6949+
RoleName=default_role_name, AssumeRolePolicyDocument=str(permissions_policy)
6950+
)
6951+
6952+
LOGGER.warning("Created new sagemaker execution role: %s", default_role_name)
6953+
6954+
iam_client.attach_role_policy(
6955+
PolicyArn="arn:aws:iam::aws:policy/AmazonSageMakerFullAccess",
6956+
RoleName=default_role_name,
6957+
)
6958+
return iam_client.get_role(RoleName=default_role_name)["Role"]["Arn"]
6959+
69226960
message = (
69236961
"The current AWS identity is not a role: {}, therefore it cannot be used as a "
69246962
"SageMaker execution role"

0 commit comments

Comments
 (0)