-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtemplate.yml
369 lines (345 loc) · 12.6 KB
/
template.yml
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
AWSTemplateFormatVersion: 2010-09-09
Description: 'Amazon OpenSearch Serverless template to create an IAM user, encryption policy, data access policy and collection'
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Required Parameters
Parameters:
- BedrockNotebookName
ParameterLabels:
BedrockNotebookName:
default: Name of SageMaker Notebook Instance
Parameters:
IAMUserArn:
AllowedPattern: "^arn:aws:iam::\\d{12}:user/[\\w+=,.@-]+|arn:aws:sts::\\d{12}:assumed-role/[\\w+=,.@-]+/[\\w+=,.@-]+$"
Description: The Arn of the IAM user (or assumed role) running this CloudFormation template.
Type: String
AOSSCollectionName:
Default: sagemaker-kb
Type: String
Description: Name of the Amazon OpenSearch Service Serverless (AOSS) collection.
MinLength: 1
MaxLength: 21
AllowedPattern: ^[a-z0-9](-*[a-z0-9])*
ConstraintDescription: Must be lowercase or numbers with a length of 1-63 characters.
AOSSIndexName:
Default: sagemaker-readthedocs-io
Type: String
Description: Name of the vector index in the Amazon OpenSearch Service Serverless (AOSS) collection.
Resources:
CodeRepository:
Type: AWS::SageMaker::CodeRepository
Properties:
GitConfig:
RepositoryUrl: https://github.com/aws-samples/bedrock-kb-rag-workshop
S3Bucket:
Type: AWS::S3::Bucket
Description: Creating Amazon S3 bucket to hold source data for knowledge base
Properties:
BucketName: !Join
- '-'
- - !Ref AOSSCollectionName
- !Sub ${AWS::AccountId}
cleanupBucketOnDelete:
Type: Custom::cleanupbucket
Properties:
ServiceToken: !GetAtt 'DeleteS3Bucket.Arn'
BucketName: !Ref S3Bucket
DependsOn: S3Bucket
DeleteS3Bucket:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Description: "Delete all objects in S3 bucket"
Timeout: 30
Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
Runtime: python3.9
Environment:
Variables:
BUCKET_NAME: !Ref S3Bucket
Code:
ZipFile: |
import json, boto3, logging
import cfnresponse
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("event: {}".format(event))
try:
bucket = event['ResourceProperties']['BucketName']
logger.info("bucket: {}, event['RequestType']: {}".format(bucket,event['RequestType']))
if event['RequestType'] == 'Delete':
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket)
for obj in bucket.objects.filter():
logger.info("delete obj: {}".format(obj))
s3.Object(bucket.name, obj.key).delete()
sendResponseCfn(event, context, cfnresponse.SUCCESS)
except Exception as e:
logger.info("Exception: {}".format(e))
sendResponseCfn(event, context, cfnresponse.FAILED)
def sendResponseCfn(event, context, responseStatus):
responseData = {}
responseData['Data'] = {}
cfnresponse.send(event, context, responseStatus, responseData, "CustomResourcePhysicalID")
CustomSGResource:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt 'CustomFunctionCopyContentsToS3Bucket.Arn'
LambdaBasicExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: S3Access
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- s3:*
Resource: '*'
CustomFunctionCopyContentsToS3Bucket:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Description: "Copies files from the Blog bucket to bucket in this account"
Timeout: 30
Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
Runtime: python3.9
Environment:
Variables:
AOSS_COLLECTION_NAME: !Ref AOSSCollectionName
Code:
ZipFile: |
import os
import json
import boto3
import logging
import cfnresponse
logger = logging.getLogger()
logger.setLevel(logging.INFO)
DATA_BUCKET = "aws-blogs-artifacts-public"
SRC_PREFIX = "artifacts/ML-15729"
MANIFEST = os.path.join(SRC_PREFIX, "manifest.txt")
# s3://aws-blogs-artifacts-public/artifacts/ML-15729/docs/manifest.txt
def lambda_handler(event, context):
logger.info('got event {}'.format(event))
if event['RequestType'] == 'Delete':
logger.info(f"copy files function called at the time of stack deletion, skipping")
response = dict(files_copied=0, error=None)
cfnresponse.send(event, context, cfnresponse.SUCCESS, response)
return
try:
s3 = boto3.client('s3')
obj = s3.get_object(Bucket=DATA_BUCKET, Key=MANIFEST)
manifest_data = obj['Body'].iter_lines()
ctr = 0
for f in manifest_data:
fname = f.decode()
key = os.path.join(SRC_PREFIX, fname)
logger.info(f"going to read {key} from bucket={DATA_BUCKET}")
copy_source = { 'Bucket': DATA_BUCKET, 'Key': key }
account_id = boto3.client('sts').get_caller_identity().get('Account')
bucket = boto3.resource('s3').Bucket(f"{os.environ.get('AOSS_COLLECTION_NAME')}-{account_id}")
dst_key = fname
logger.info(f"going to copy {copy_source} -> s3://{bucket}/{dst_key}")
bucket.copy(copy_source, dst_key)
ctr += 1
response = dict(files_copied=ctr, error=None)
cfnresponse.send(event, context, cfnresponse.SUCCESS, response)
except Exception as e:
logger.error(e)
response = dict(files_copied=0, error=str(e))
cfnresponse.send(event, context, cfnresponse.FAILED, response)
return
AmazonBedrockExecutionRoleForKnowledgeBase:
Type: AWS::IAM::Role
Properties:
RoleName: !Join
- '-'
- - AmazonBedrockExecutionRoleForKnowledgeBase
- !Ref AOSSCollectionName
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: bedrock.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
"aws:SourceAccount": !Sub "${AWS::AccountId}"
ArnLike:
"AWS:SourceArn": !Sub "arn:aws:bedrock:${AWS::Region}:${AWS::AccountId}:knowledge-base/*"
Path: /
Policies:
- PolicyName: S3ReadOnlyAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:Get*
- s3:List*
- s3:Describe*
- s3-object-lambda:Get*,
- s3-object-lambda:List*
Resource: '*'
- PolicyName: AOSSAPIAccessAll
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- aoss:APIAccessAll
Resource: !Sub arn:aws:aoss:${AWS::Region}:${AWS::AccountId}:collection/*
- PolicyName: BedrockListAndInvokeModel
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- bedrock:ListCustomModels
Resource: '*'
- Effect: Allow
Action:
- bedrock:InvokeModel
Resource: !Sub arn:aws:bedrock:${AWS::Region}::foundation-model/*
AmazonBedrockExecutionRoleForAgentsQA:
Type: AWS::IAM::Role
Properties:
RoleName: AmazonBedrockExecutionRoleForAgents_SageMakerQA
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: bedrock.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSageMakerFullAccess
- arn:aws:iam::aws:policy/AmazonBedrockFullAccess
NotebookInstance:
Type: AWS::SageMaker::NotebookInstance
Properties:
NotebookInstanceName: !Sub ${AWS::StackName}-notebook
InstanceType: ml.t3.xlarge
RoleArn: !GetAtt NotebookRole.Arn
DefaultCodeRepository: !GetAtt CodeRepository.CodeRepositoryName
NotebookRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Join
- '-'
- - !Ref AOSSCollectionName
- NoteBookRole
Policies:
- PolicyName: CustomNotebookAccess
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: BedrockFullAccess
Effect: Allow
Action:
- "bedrock:*"
Resource: "*"
- PolicyName: AOSSAPIAccessAll
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- aoss:APIAccessAll
Resource: !Sub arn:aws:aoss:${AWS::Region}:${AWS::AccountId}:collection/*
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSageMakerFullAccess
- arn:aws:iam::aws:policy/AmazonS3FullAccess
- arn:aws:iam::aws:policy/AWSCloudFormationReadOnlyAccess
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- sagemaker.amazonaws.com
Action:
- 'sts:AssumeRole'
- Effect: Allow
Principal:
Service:
- bedrock.amazonaws.com
Action:
- 'sts:AssumeRole'
DataAccessPolicy:
Type: 'AWS::OpenSearchServerless::AccessPolicy'
Properties:
Name: !Join
- '-'
- - !Ref AOSSCollectionName
- access-policy
Type: data
Description: Access policy for AOSS collection
Policy: !Sub >-
[{"Description":"Access for cfn user","Rules":[{"ResourceType":"index","Resource":["index/*/*"],"Permission":["aoss:*"]},
{"ResourceType":"collection","Resource":["collection/quickstart"],"Permission":["aoss:*"]}],
"Principal":["${IAMUserArn}", "${AmazonBedrockExecutionRoleForKnowledgeBase.Arn}", "${NotebookRole.Arn}"]}]
NetworkPolicy:
Type: 'AWS::OpenSearchServerless::SecurityPolicy'
Properties:
Name: !Join
- '-'
- - !Ref AOSSCollectionName
- network-policy
Type: network
Description: Network policy for AOSS collection
Policy: !Sub >-
[{"Rules":[{"ResourceType":"collection","Resource":["collection/${AOSSCollectionName}"]}, {"ResourceType":"dashboard","Resource":["collection/${AOSSCollectionName}"]}],"AllowFromPublic":true}]
EncryptionPolicy:
Type: 'AWS::OpenSearchServerless::SecurityPolicy'
Properties:
Name: !Join
- '-'
- - !Ref AOSSCollectionName
- security-policy
Type: encryption
Description: Encryption policy for AOSS collection
Policy: !Sub >-
{"Rules":[{"ResourceType":"collection","Resource":["collection/${AOSSCollectionName}"]}],"AWSOwnedKey":true}
Collection:
Type: 'AWS::OpenSearchServerless::Collection'
Properties:
Name: !Ref AOSSCollectionName
Type: VECTORSEARCH
Description: Collection to holds vector search data
DependsOn: EncryptionPolicy
Outputs:
S3Bucket:
Value: !GetAtt S3Bucket.Arn
DashboardURL:
Value: !GetAtt Collection.DashboardEndpoint
CollectionARN:
Value: !GetAtt Collection.Arn
FilesCopied:
Description: Files copied
Value: !GetAtt 'CustomSGResource.files_copied'
FileCopyError:
Description: Files copy error
Value: !GetAtt 'CustomSGResource.error'
AOSSVectorIndexName:
Description: vector index
Value: !Ref AOSSIndexName
Region:
Description: Deployed Region
Value: !Ref AWS::Region