@@ -6902,13 +6902,16 @@ def production_variant(
6902
6902
return production_variant_configuration
6903
6903
6904
6904
6905
- def get_execution_role (sagemaker_session = None ):
6905
+ def get_execution_role (sagemaker_session = None , use_default = False ):
6906
6906
"""Return the role ARN whose credentials are used to call the API.
6907
6907
6908
6908
Throws an exception if role doesn't exist.
6909
6909
6910
6910
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``.
6912
6915
6913
6916
Returns:
6914
6917
(str): The role ARN
@@ -6919,6 +6922,41 @@ def get_execution_role(sagemaker_session=None):
6919
6922
6920
6923
if ":role/" in arn :
6921
6924
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
+
6922
6960
message = (
6923
6961
"The current AWS identity is not a role: {}, therefore it cannot be used as a "
6924
6962
"SageMaker execution role"
0 commit comments