forked from aws-samples/amazon-bedrock-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.py
310 lines (281 loc) · 10.4 KB
/
utility.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import json
import boto3
import random
import time
suffix = random.randrange(200, 900)
boto3_session = boto3.session.Session()
region_name = boto3_session.region_name
iam_client = boto3_session.client('iam')
account_number = boto3.client('sts').get_caller_identity().get('Account')
identity = boto3.client('sts').get_caller_identity()['Arn']
encryption_policy_name = f"bedrock-sample-rag-sp-{suffix}"
network_policy_name = f"bedrock-sample-rag-np-{suffix}"
access_policy_name = f'bedrock-sample-rag-ap-{suffix}'
bedrock_execution_role_name = f'AmazonBedrockExecutionRoleForKnowledgeBase_{suffix}'
fm_policy_name = f'AmazonBedrockFoundationModelPolicyForKnowledgeBase_{suffix}'
s3_policy_name = f'AmazonBedrockS3PolicyForKnowledgeBase_{suffix}'
oss_policy_name = f'AmazonBedrockOSSPolicyForKnowledgeBase_{suffix}'
def create_bedrock_execution_role(bucket_name):
foundation_model_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
],
"Resource": [
f"arn:aws:bedrock:{region_name}::foundation-model/amazon.titan-embed-text-v1"
]
}
]
}
s3_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
f"arn:aws:s3:::{bucket_name}",
f"arn:aws:s3:::{bucket_name}/*"
],
"Condition": {
"StringEquals": {
"aws:ResourceAccount": f"{account_number}"
}
}
}
]
}
assume_role_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "bedrock.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
# create policies based on the policy documents
fm_policy = iam_client.create_policy(
PolicyName=fm_policy_name,
PolicyDocument=json.dumps(foundation_model_policy_document),
Description='Policy for accessing foundation model',
)
s3_policy = iam_client.create_policy(
PolicyName=s3_policy_name,
PolicyDocument=json.dumps(s3_policy_document),
Description='Policy for reading documents from s3')
# create bedrock execution role
bedrock_kb_execution_role = iam_client.create_role(
RoleName=bedrock_execution_role_name,
AssumeRolePolicyDocument=json.dumps(assume_role_policy_document),
Description='Amazon Bedrock Knowledge Base Execution Role for accessing OSS and S3',
MaxSessionDuration=3600
)
# fetch arn of the policies and role created above
bedrock_kb_execution_role_arn = bedrock_kb_execution_role['Role']['Arn']
s3_policy_arn = s3_policy["Policy"]["Arn"]
fm_policy_arn = fm_policy["Policy"]["Arn"]
# attach policies to Amazon Bedrock execution role
iam_client.attach_role_policy(
RoleName=bedrock_kb_execution_role["Role"]["RoleName"],
PolicyArn=fm_policy_arn
)
iam_client.attach_role_policy(
RoleName=bedrock_kb_execution_role["Role"]["RoleName"],
PolicyArn=s3_policy_arn
)
return bedrock_kb_execution_role
def create_oss_policy_attach_bedrock_execution_role(collection_id, bedrock_kb_execution_role):
# define oss policy document
oss_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"aoss:APIAccessAll"
],
"Resource": [
f"arn:aws:aoss:{region_name}:{account_number}:collection/{collection_id}"
]
}
]
}
oss_policy = iam_client.create_policy(
PolicyName=oss_policy_name,
PolicyDocument=json.dumps(oss_policy_document),
Description='Policy for accessing opensearch serverless',
)
oss_policy_arn = oss_policy["Policy"]["Arn"]
print("Opensearch serverless arn: ", oss_policy_arn)
iam_client.attach_role_policy(
RoleName=bedrock_kb_execution_role["Role"]["RoleName"],
PolicyArn=oss_policy_arn
)
return None
def create_policies_in_oss(vector_store_name, aoss_client, bedrock_kb_execution_role_arn):
encryption_policy = aoss_client.create_security_policy(
name=encryption_policy_name,
policy=json.dumps(
{
'Rules': [{'Resource': ['collection/' + vector_store_name],
'ResourceType': 'collection'}],
'AWSOwnedKey': True
}),
type='encryption'
)
network_policy = aoss_client.create_security_policy(
name=network_policy_name,
policy=json.dumps(
[
{'Rules': [{'Resource': ['collection/' + vector_store_name],
'ResourceType': 'collection'}],
'AllowFromPublic': True}
]),
type='network'
)
access_policy = aoss_client.create_access_policy(
name=access_policy_name,
policy=json.dumps(
[
{
'Rules': [
{
'Resource': ['collection/' + vector_store_name],
'Permission': [
'aoss:CreateCollectionItems',
'aoss:DeleteCollectionItems',
'aoss:UpdateCollectionItems',
'aoss:DescribeCollectionItems'],
'ResourceType': 'collection'
},
{
'Resource': ['index/' + vector_store_name + '/*'],
'Permission': [
'aoss:CreateIndex',
'aoss:DeleteIndex',
'aoss:UpdateIndex',
'aoss:DescribeIndex',
'aoss:ReadDocument',
'aoss:WriteDocument'],
'ResourceType': 'index'
}],
'Principal': [identity, bedrock_kb_execution_role_arn],
'Description': 'Easy data policy'}
]),
type='data'
)
return encryption_policy, network_policy, access_policy
def delete_iam_role_and_policies():
fm_policy_arn = f"arn:aws:iam::{account_number}:policy/{fm_policy_name}"
s3_policy_arn = f"arn:aws:iam::{account_number}:policy/{s3_policy_name}"
oss_policy_arn = f"arn:aws:iam::{account_number}:policy/{oss_policy_name}"
iam_client.detach_role_policy(
RoleName=bedrock_execution_role_name,
PolicyArn=s3_policy_arn
)
iam_client.detach_role_policy(
RoleName=bedrock_execution_role_name,
PolicyArn=fm_policy_arn
)
iam_client.detach_role_policy(
RoleName=bedrock_execution_role_name,
PolicyArn=oss_policy_arn
)
iam_client.delete_role(RoleName=bedrock_execution_role_name)
iam_client.delete_policy(PolicyArn=s3_policy_arn)
iam_client.delete_policy(PolicyArn=fm_policy_arn)
iam_client.delete_policy(PolicyArn=oss_policy_arn)
return 0
def interactive_sleep(seconds: int):
dots = ''
for i in range(seconds):
dots += '.'
print(dots, end='\r')
time.sleep(1)
print('Done!')
def create_bedrock_execution_role_multi_ds(bucket_names):
foundation_model_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
],
"Resource": [
f"arn:aws:bedrock:{region_name}::foundation-model/amazon.titan-embed-text-v1"
]
}
]
}
s3_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [item for sublist in [[f'arn:aws:s3:::{bucket}', f'arn:aws:s3:::{bucket}/*'] for bucket in bucket_names] for item in sublist],
"Condition": {
"StringEquals": {
"aws:ResourceAccount": f"{account_number}"
}
}
}
]
}
assume_role_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "bedrock.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
# create policies based on the policy documents
fm_policy = iam_client.create_policy(
PolicyName=fm_policy_name,
PolicyDocument=json.dumps(foundation_model_policy_document),
Description='Policy for accessing foundation model',
)
s3_policy = iam_client.create_policy(
PolicyName=s3_policy_name,
PolicyDocument=json.dumps(s3_policy_document),
Description='Policy for reading documents from s3')
# create bedrock execution role
bedrock_kb_execution_role = iam_client.create_role(
RoleName=bedrock_execution_role_name,
AssumeRolePolicyDocument=json.dumps(assume_role_policy_document),
Description='Amazon Bedrock Knowledge Base Execution Role for accessing OSS and S3',
MaxSessionDuration=3600
)
# fetch arn of the policies and role created above
bedrock_kb_execution_role_arn = bedrock_kb_execution_role['Role']['Arn']
s3_policy_arn = s3_policy["Policy"]["Arn"]
fm_policy_arn = fm_policy["Policy"]["Arn"]
# attach policies to Amazon Bedrock execution role
iam_client.attach_role_policy(
RoleName=bedrock_kb_execution_role["Role"]["RoleName"],
PolicyArn=fm_policy_arn
)
iam_client.attach_role_policy(
RoleName=bedrock_kb_execution_role["Role"]["RoleName"],
PolicyArn=s3_policy_arn
)
return bedrock_kb_execution_role