9
9
# get the ARN of the user
10
10
caller_arn = boto3 .client ('sts' ).get_caller_identity ()['Arn' ]
11
11
12
+
12
13
def create_execution_role (role_name = "basic-role" ):
13
14
"""Create an service role to procure services on your behalf
15
+
14
16
15
17
Args:
16
18
role_name (str): name of the role
@@ -19,19 +21,31 @@ def create_execution_role(role_name="basic-role"):
19
21
dict
20
22
"""
21
23
# if the role already exists, delete it
22
-
23
24
# Note: you need to make sure the role is not
24
25
# used in production, because the code below
25
26
# 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 ):
30
36
role = boto3 .resource ('iam' ).Role (role_name )
31
-
32
37
for p in role .attached_policies .all ():
33
38
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 )
35
49
36
50
# Trust policy document
37
51
trust_relation_policy_doc = {
@@ -51,17 +65,13 @@ def create_execution_role(role_name="basic-role"):
51
65
}
52
66
53
67
54
- if role is not None :
55
- iam .delete_role (RoleName = role .name )
56
-
57
68
res = iam .create_role (
58
69
RoleName = role_name ,
59
70
AssumeRolePolicyDocument = json .dumps (trust_relation_policy_doc )
60
71
)
61
72
return res
62
73
63
74
64
-
65
75
def attach_permission (role_name , policy_name , policy_doc ):
66
76
"""Attach a basic permission policy to the role"""
67
77
0 commit comments