Skip to content

Commit b8eab04

Browse files
authored
Merge pull request #2 from hsl89/execution-role
Execution role
2 parents 1063e2f + 610513e commit b8eab04

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

sagemaker-fundamentals/execution-role/iam_helpers.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@
99
# get the ARN of the user
1010
caller_arn = boto3.client('sts').get_caller_identity()['Arn']
1111

12+
1213
def create_execution_role(role_name="basic-role"):
1314
"""Create an service role to procure services on your behalf
15+
1416
1517
Args:
1618
role_name (str): name of the role
@@ -19,19 +21,31 @@ def create_execution_role(role_name="basic-role"):
1921
dict
2022
"""
2123
# if the role already exists, delete it
22-
2324
# Note: you need to make sure the role is not
2425
# used in production, because the code below
2526
# will delete the role and create a new one
26-
role = None
27-
for rol in iam.list_roles()['Roles']:
28-
if rol['RoleName'] == role_name:
29-
# detach policy from the role before deleting it
27+
28+
def find_role(role_res, role_name):
29+
for r in role_res['Roles']:
30+
if r['RoleName'] == role_name:
31+
return True
32+
return False
33+
34+
def delete_role(role_res, role_name):
35+
if find_role(role_res, role_name):
3036
role = boto3.resource('iam').Role(role_name)
31-
3237
for p in role.attached_policies.all():
3338
role.detach_policy(PolicyArn=p.arn)
34-
break
39+
40+
iam.delete_role(RoleName=role.name)
41+
return
42+
43+
role_res = iam.list_roles(MaxItems=10)
44+
delete_role(role_res, role_name)
45+
46+
while 'Marker' in role_res:
47+
role_res = iam.list_roles(MaxItems=10, Marker=role_res['Marker'])
48+
delete_role(role_res, role_name)
3549

3650
# Trust policy document
3751
trust_relation_policy_doc = {
@@ -51,17 +65,13 @@ def create_execution_role(role_name="basic-role"):
5165
}
5266

5367

54-
if role is not None:
55-
iam.delete_role(RoleName=role.name)
56-
5768
res = iam.create_role(
5869
RoleName=role_name,
5970
AssumeRolePolicyDocument=json.dumps(trust_relation_policy_doc)
6071
)
6172
return res
6273

6374

64-
6575
def attach_permission(role_name, policy_name, policy_doc):
6676
"""Attach a basic permission policy to the role"""
6777

0 commit comments

Comments
 (0)