@@ -6780,13 +6780,16 @@ def production_variant(
6780
6780
return production_variant_configuration
6781
6781
6782
6782
6783
- def get_execution_role (sagemaker_session = None ):
6783
+ def get_execution_role (sagemaker_session = None , use_default = False ):
6784
6784
"""Return the role ARN whose credentials are used to call the API.
6785
6785
6786
6786
Throws an exception if role doesn't exist.
6787
6787
6788
6788
Args:
6789
- sagemaker_session(Session): Current sagemaker session
6789
+ sagemaker_session(Session): Current sagemaker session.
6790
+ use_default(bool): Use a default role if `get_caller_identity_arn does not
6791
+ return a correct role. This default role will be created if needed.
6792
+ Defaults to ``False``.
6790
6793
6791
6794
Returns:
6792
6795
(str): The role ARN
@@ -6797,6 +6800,41 @@ def get_execution_role(sagemaker_session=None):
6797
6800
6798
6801
if ":role/" in arn :
6799
6802
return arn
6803
+
6804
+ if use_default :
6805
+ default_role_name = "AmazonSageMaker-DefaultRole"
6806
+
6807
+ LOGGER .warning ("Using default role: %s" , default_role_name )
6808
+
6809
+ boto3_session = sagemaker_session .boto_session
6810
+ permissions_policy = json .dumps (
6811
+ {
6812
+ "Version" : "2012-10-17" ,
6813
+ "Statement" : [
6814
+ {
6815
+ "Effect" : "Allow" ,
6816
+ "Principal" : {"Service" : ["sagemaker.amazonaws.com" ]},
6817
+ "Action" : "sts:AssumeRole" ,
6818
+ }
6819
+ ],
6820
+ }
6821
+ )
6822
+ iam_client = boto3_session .client ("iam" )
6823
+ try :
6824
+ iam_client .get_role (RoleName = default_role_name )
6825
+ except iam_client .exceptions .NoSuchEntityException :
6826
+ iam_client .create_role (
6827
+ RoleName = default_role_name , AssumeRolePolicyDocument = str (permissions_policy )
6828
+ )
6829
+
6830
+ LOGGER .warning ("Created new sagemaker execution role: %s" , default_role_name )
6831
+
6832
+ iam_client .attach_role_policy (
6833
+ PolicyArn = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess" ,
6834
+ RoleName = default_role_name ,
6835
+ )
6836
+ return iam_client .get_role (RoleName = default_role_name )["Role" ]["Arn" ]
6837
+
6800
6838
message = (
6801
6839
"The current AWS identity is not a role: {}, therefore it cannot be used as a "
6802
6840
"SageMaker execution role"
0 commit comments