-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathinstaller.py
More file actions
4074 lines (3584 loc) · 161 KB
/
installer.py
File metadata and controls
4074 lines (3584 loc) · 161 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
AWS Infrastructure Installer using boto3
This script creates AWS infrastructure resources equivalent to the CDK stack.
"""
import boto3
import json
import time
import logging
import argparse
import base64
import ipaddress
from typing import Dict, List, Optional
from botocore.exceptions import ClientError
import urllib.request
import urllib.error
# Configuration
project_name = "strands" # at least 3 characters
region = "us-west-2"
git_name = "strands-agent"
sts_client = boto3.client("sts", region_name=region)
account_id = sts_client.get_caller_identity()["Account"]
vector_index_name = project_name
custom_header_name = "X-Custom-Header"
custom_header_value = f"{project_name}_12dab15e4s31"
# Initialize boto3 clients
s3_client = boto3.client("s3", region_name=region)
iam_client = boto3.client("iam", region_name=region)
secrets_client = boto3.client("secretsmanager", region_name=region)
opensearch_client = boto3.client("opensearchserverless", region_name=region)
ec2_client = boto3.client("ec2", region_name=region)
elbv2_client = boto3.client("elbv2", region_name=region)
cloudfront_client = boto3.client("cloudfront", region_name=region)
lambda_client = boto3.client("lambda", region_name=region)
ssm_client = boto3.client("ssm", region_name=region)
bucket_name = f"storage-for-{project_name}-{account_id}-{region}"
# Configure logging
def setup_logging(log_level=logging.INFO):
"""Setup logging configuration."""
log_format = "%(asctime)s - %(levelname)s - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"
logging.basicConfig(
level=log_level,
format=log_format,
datefmt=date_format,
handlers=[
logging.StreamHandler()
#logging.FileHandler(f"installer_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
]
)
return logging.getLogger(__name__)
logger = setup_logging()
def create_s3_bucket() -> str:
"""Create S3 bucket with CORS configuration."""
logger.info(f"[1/10] Creating S3 bucket: {bucket_name}")
try:
# Create bucket
logger.debug(f"Creating bucket in region: {region}")
if region == "us-east-1":
s3_client.create_bucket(Bucket=bucket_name)
else:
s3_client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={"LocationConstraint": region}
)
logger.debug("Bucket created successfully")
# Configure bucket
logger.debug("Configuring public access block")
s3_client.put_public_access_block(
Bucket=bucket_name,
PublicAccessBlockConfiguration={
"BlockPublicAcls": True,
"IgnorePublicAcls": True,
"BlockPublicPolicy": True,
"RestrictPublicBuckets": True
}
)
# Set CORS configuration
logger.debug("Setting CORS configuration")
cors_configuration = {
"CORSRules": [
{
"AllowedHeaders": ["*"],
"AllowedMethods": ["GET", "POST", "PUT"],
"AllowedOrigins": ["*"]
}
]
}
s3_client.put_bucket_cors(
Bucket=bucket_name,
CORSConfiguration=cors_configuration
)
# Enable versioning (set to false means suspend)
logger.debug("Configuring versioning")
s3_client.put_bucket_versioning(
Bucket=bucket_name,
VersioningConfiguration={"Status": "Suspended"}
)
# Create docs folder
logger.debug("Creating docs folder")
try:
s3_client.put_object(
Bucket=bucket_name,
Key="docs/",
Body=b""
)
logger.debug("docs folder created successfully")
except ClientError as e:
logger.warning(f"Failed to create docs folder: {e}")
logger.info(f"✓ S3 bucket created successfully: {bucket_name}")
return bucket_name
except ClientError as e:
if e.response["Error"]["Code"] in ["BucketAlreadyExists", "BucketAlreadyOwnedByYou"]:
logger.warning(f"S3 bucket already exists: {bucket_name}")
# Create docs folder if bucket already exists
logger.debug("Creating docs folder in existing bucket")
try:
s3_client.put_object(
Bucket=bucket_name,
Key="docs/",
Body=b""
)
logger.debug("docs folder created successfully")
except ClientError as folder_error:
if folder_error.response["Error"]["Code"] != "NoSuchBucket":
logger.warning(f"Failed to create docs folder: {folder_error}")
return bucket_name
logger.error(f"Failed to create S3 bucket: {e}")
raise
def create_iam_role(role_name: str, assume_role_policy: Dict, managed_policies: Optional[List[str]] = None) -> str:
"""Create IAM role."""
logger.debug(f"Creating IAM role: {role_name}")
try:
response = iam_client.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps(assume_role_policy),
Description=f"Role for {role_name}"
)
role_arn = response["Role"]["Arn"]
logger.debug(f"Role created: {role_arn}")
if managed_policies:
logger.debug(f"Attaching {len(managed_policies)} managed policies")
for policy_arn in managed_policies:
iam_client.attach_role_policy(
RoleName=role_name,
PolicyArn=policy_arn
)
logger.debug(f"Attached policy: {policy_arn}")
logger.info(f"✓ IAM role created: {role_name}")
return role_arn
except ClientError as e:
if e.response["Error"]["Code"] == "EntityAlreadyExists":
logger.warning(f"IAM role already exists: {role_name}")
response = iam_client.get_role(RoleName=role_name)
role_arn = response["Role"]["Arn"]
# Update managed policies if provided
if managed_policies:
logger.debug(f"Updating managed policies for existing role")
# Get currently attached managed policies
try:
attached_policies = iam_client.list_attached_role_policies(RoleName=role_name)
current_policy_arns = {policy["PolicyArn"] for policy in attached_policies["AttachedPolicies"]}
# Attach missing policies
for policy_arn in managed_policies:
if policy_arn not in current_policy_arns:
iam_client.attach_role_policy(
RoleName=role_name,
PolicyArn=policy_arn
)
logger.debug(f"Attached missing policy: {policy_arn}")
except ClientError as policy_error:
logger.warning(f"Could not update managed policies: {policy_error}")
return role_arn
logger.error(f"Failed to create IAM role {role_name}: {e}")
raise
def attach_inline_policy(role_name: str, policy_name: str, policy_document: Dict):
"""Attach or update inline policy to IAM role."""
logger.debug(f"Attaching/updating inline policy {policy_name} to {role_name}")
try:
iam_client.put_role_policy(
RoleName=role_name,
PolicyName=policy_name,
PolicyDocument=json.dumps(policy_document)
)
logger.debug(f"Policy {policy_name} attached/updated successfully")
except ClientError as e:
logger.error(f"Error attaching/updating policy {policy_name}: {e}")
raise
def create_knowledge_base_role() -> str:
"""Create Knowledge Base IAM role."""
logger.info("[2/10] Creating Knowledge Base IAM role")
role_name = f"role-knowledge-base-for-{project_name}-{region}"
assume_role_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "bedrock.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
role_arn = create_iam_role(role_name, assume_role_policy)
# Always attach/update inline policies (put_role_policy will create or update)
bedrock_invoke_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:*",
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream",
"bedrock:GetInferenceProfile",
"bedrock:GetFoundationModel"
],
"Resource": [
"*",
f"arn:aws:bedrock:{region}:{account_id}:inference-profile/*",
f"arn:aws:bedrock:{region}:*:inference-profile/*",
"arn:aws:bedrock:*::foundation-model/*"
]
}
]
}
attach_inline_policy(role_name, f"bedrock-invoke-policy-for-{project_name}", bedrock_invoke_policy)
s3_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:*"],
"Resource": ["*"]
}
]
}
attach_inline_policy(role_name, f"knowledge-base-s3-policy-for-{project_name}", s3_policy)
opensearch_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["aoss:APIAccessAll"],
"Resource": ["*"]
}
]
}
attach_inline_policy(role_name, f"bedrock-agent-opensearch-policy-for-{project_name}", opensearch_policy)
bedrock_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:*",
"bedrock:GetInferenceProfile"
],
"Resource": [
"*",
f"arn:aws:bedrock:{region}:*:inference-profile/*"
]
}
]
}
attach_inline_policy(role_name, f"bedrock-agent-bedrock-policy-for-{project_name}", bedrock_policy)
return role_arn
def create_agent_role() -> str:
"""Create Agent IAM role."""
logger.info("[2/10] Creating Agent IAM role")
role_name = f"role-agent-for-{project_name}-{region}"
assume_role_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "bedrock.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
role_arn = create_iam_role(role_name, assume_role_policy, ["arn:aws:iam::aws:policy/AWSLambdaExecute"])
# Always attach/update inline policies
bedrock_retrieve_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["bedrock:Retrieve"],
"Resource": [f"arn:aws:bedrock:{region}:{account_id}:knowledge-base/*"]
}
]
}
attach_inline_policy(role_name, f"bedrock-retrieve-policy-for-{project_name}", bedrock_retrieve_policy)
inference_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream",
"bedrock:GetInferenceProfile",
"bedrock:GetFoundationModel"
],
"Resource": [
f"arn:aws:bedrock:{region}:{account_id}:inference-profile/*",
"arn:aws:bedrock:*::foundation-model/*"
]
}
]
}
attach_inline_policy(role_name, f"agent-inference-policy-for-{project_name}", inference_policy)
lambda_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["lambda:InvokeFunction", "cloudwatch:*"],
"Resource": ["*"]
}
]
}
attach_inline_policy(role_name, f"lambda-invoke-policy-for-{project_name}", lambda_policy)
bedrock_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["bedrock:*"],
"Resource": ["*"]
}
]
}
attach_inline_policy(role_name, f"bedrock-policy-agent-for-{project_name}", bedrock_policy)
return role_arn
def create_ec2_role(knowledge_base_role_arn: str) -> str:
"""Create EC2 IAM role."""
logger.info("[2/10] Creating EC2 IAM role")
role_name = f"role-ec2-for-{project_name}-{region}"
assume_role_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": ["ec2.amazonaws.com", "bedrock.amazonaws.com"]
},
"Action": "sts:AssumeRole"
}
]
}
managed_policies = [
"arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy",
"arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
]
role_arn = create_iam_role(role_name, assume_role_policy, managed_policies)
# Attach inline policies
policies = [
{
"name": f"secret-manager-policy-ec2-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue"],
"Resource": ["*"]
}
]
}
},
{
"name": f"pvre-policy-ec2-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["ssm:*", "ssmmessages:*", "ec2messages:*", "tag:*"],
"Resource": ["*"]
}
]
}
},
{
"name": f"bedrock-policy-ec2-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["bedrock:*"],
"Resource": ["*"]
},
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": [
"arn:aws:bedrock:*:*:inference-profile/*",
"arn:aws:bedrock:us-west-2:*:foundation-model/*",
"arn:aws:bedrock:us-east-1:*:foundation-model/*",
"arn:aws:bedrock:us-east-2:*:foundation-model/*",
"arn:aws:bedrock:ap-northeast-2:*:foundation-model/*"
]
}
]
}
},
{
"name": f"cost-explorer-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["ce:GetCostAndUsage"],
"Resource": ["*"]
}
]
}
},
{
"name": f"ec2-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["ec2:*"],
"Resource": ["*"]
}
]
}
},
{
"name": f"lambda-invoke-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["lambda:InvokeFunction"],
"Resource": ["*"]
}
]
}
},
{
"name": f"efs-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["ec2:DescribeFileSystems", "elasticfilesystem:DescribeFileSystems"],
"Resource": ["*"]
}
]
}
},
{
"name": f"cognito-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cognito-idp:ListUserPools",
"cognito-idp:DescribeUserPool",
"cognito-idp:ListUserPoolClients",
"cognito-idp:DescribeUserPoolClient"
],
"Resource": ["*"]
}
]
}
},
{
"name": f"bedrock-agentcore-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["bedrock-agentcore:*"],
"Resource": ["*"]
}
]
}
},
{
"name": f"pass-role-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iam:PassRole"],
"Resource": [knowledge_base_role_arn]
}
]
}
},
{
"name": f"aoss-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["aoss:*"],
"Resource": ["*"]
}
]
}
},
{
"name": f"getRole-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iam:GetRole"],
"Resource": ["*"]
}
]
}
},
{
"name": f"s3-bucket-access-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:*"],
"Resource": ["*"]
}
]
}
},
{
"name": f"cloudwatch-logs-policy-for-{project_name}",
"document": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:GetLogEvents",
"logs:FilterLogEvents",
"logs:GetLogGroupFields",
"logs:GetLogRecord",
"logs:GetQueryResults",
"logs:StartQuery",
"logs:StopQuery"
],
"Resource": ["*"]
}
]
}
}
]
for policy in policies:
attach_inline_policy(role_name, policy["name"], policy["document"])
# Create instance profile
instance_profile_name = f"instance-profile-{project_name}-{region}"
try:
iam_client.create_instance_profile(InstanceProfileName=instance_profile_name)
iam_client.add_role_to_instance_profile(
InstanceProfileName=instance_profile_name,
RoleName=role_name
)
except ClientError as e:
if e.response["Error"]["Code"] != "EntityAlreadyExists":
raise
return role_arn
def create_secrets() -> Dict[str, str]:
"""Create Secrets Manager secrets."""
logger.info("[3/10] Creating Secrets Manager secrets")
logger.info("Please enter API keys when prompted (press Enter to skip and leave empty):")
secrets = {
"tavily": {
"name": f"tavilyapikey-{project_name}",
"description": "secret for tavily api key",
"secret_value": {
"project_name": project_name,
"tavily_api_key": ""
}
},
"notion": {
"name": f"notionapikey-{project_name}",
"description": "secret for notion api key",
"secret_value": {
"project_name": project_name,
"notion_api_key": ""
}
},
"slack": {
"name": f"slackapikey-{project_name}",
"description": "secret for slack api key",
"secret_value": {
"project_name": project_name,
"slack_team_id": "",
"slack_bot_token": ""
}
}
}
secret_arns = {}
for key, secret_config in secrets.items():
# Check if secret already exists before prompting for input
try:
response = secrets_client.describe_secret(SecretId=secret_config["name"])
secret_arns[key] = response["ARN"]
logger.warning(f" Secret already exists: {secret_config['name']}")
except ClientError as e:
if e.response["Error"]["Code"] == "ResourceNotFoundException":
# Secret doesn't exist, prompt for API key and create it
if key == "tavily":
logger.info(f"Enter credential of {secret_config['name']} (Tavily API Key):")
api_key = input(f"Creating {secret_config['name']} - Tavily API Key: ").strip()
secret_config["secret_value"]["tavily_api_key"] = api_key
elif key == "notion":
logger.info(f"Enter credential of {secret_config['name']} (Notion API Key):")
api_key = input(f"Creating {secret_config['name']} - Notion API Key: ").strip()
secret_config["secret_value"]["notion_api_key"] = api_key
elif key == "slack":
logger.info(f"Enter credential of {secret_config['name']} (Slack Team ID and Bot Token):")
team_id = input(f"Creating {secret_config['name']} - Slack Team ID: ").strip()
bot_token = input(f"Creating {secret_config['name']} - Slack Bot Token: ").strip()
secret_config["secret_value"]["slack_team_id"] = team_id
secret_config["secret_value"]["slack_bot_token"] = bot_token
# Create the secret
try:
response = secrets_client.create_secret(
Name=secret_config["name"],
Description=secret_config["description"],
SecretString=json.dumps(secret_config["secret_value"])
)
secret_arns[key] = response["ARN"]
logger.info(f" ✓ Created secret: {secret_config['name']}")
except ClientError as create_error:
logger.error(f" Failed to create secret {secret_config['name']}: {create_error}")
raise
else:
logger.error(f" Failed to check secret {secret_config['name']}: {e}")
raise
logger.info(f"✓ Created {len(secret_arns)} secrets")
return secret_arns
def create_opensearch_collection(ec2_role_arn: str = None, knowledge_base_role_arn: str = None) -> Dict[str, str]:
"""Create OpenSearch Serverless collection and policies."""
logger.info("[4/10] Creating OpenSearch Serverless collection")
collection_name = vector_index_name
enc_policy_name = f"enc-{project_name}-{region}"
net_policy_name = f"net-{project_name}-{region}"
data_policy_name = f"data-{project_name}"
# Check if collection already exists first
try:
existing_collections = opensearch_client.list_collections()
for collection in existing_collections.get("collectionSummaries", []):
if collection["name"] == collection_name and collection["status"] == "ACTIVE":
logger.warning(f"OpenSearch collection already exists: {collection['name']}")
collection_arn = collection["arn"]
collection_id = collection["id"]
# Get collection endpoint
collection_details = opensearch_client.batch_get_collection(names=[collection_name])
collection_detail = collection_details["collectionDetails"][0]
collection_endpoint = collection_detail.get("collectionEndpoint")
# If endpoint is not available, wait for collection to be ready
if not collection_endpoint:
logger.info(" Collection endpoint not yet available, waiting for collection to be ready...")
wait_count = 0
while True:
response = opensearch_client.batch_get_collection(names=[collection_name])
collection_detail = response["collectionDetails"][0]
status = collection_detail.get("status")
wait_count += 1
if wait_count % 6 == 0: # Log every minute
logger.debug(f" Collection status: {status} (waited {wait_count * 10} seconds)")
if "collectionEndpoint" in collection_detail and collection_detail["collectionEndpoint"]:
collection_endpoint = collection_detail["collectionEndpoint"]
if status == "ACTIVE":
break
elif status == "ACTIVE":
# If active but no endpoint, try one more time after a short wait
time.sleep(10)
response = opensearch_client.batch_get_collection(names=[collection_name])
collection_detail = response["collectionDetails"][0]
collection_endpoint = collection_detail.get("collectionEndpoint")
if collection_endpoint:
break
if wait_count > 60: # Timeout after 10 minutes
raise Exception(f"Timeout waiting for collection endpoint. Collection status: {status}")
time.sleep(10)
# Update data access policy to include roles if needed
try:
policy_detail = opensearch_client.get_access_policy(
name=data_policy_name,
type="data"
)
current_policy = policy_detail["accessPolicyDetail"]["policy"]
# Check if roles are already in principals and update if needed
needs_update = False
roles_to_add = []
if ec2_role_arn:
roles_to_add.append(("EC2", ec2_role_arn))
if knowledge_base_role_arn:
roles_to_add.append(("Knowledge Base", knowledge_base_role_arn))
for rule in current_policy:
if "Principal" in rule:
current_principals = rule["Principal"]
if not isinstance(current_principals, list):
current_principals = [current_principals]
for role_type, role_arn in roles_to_add:
if role_arn and role_arn not in current_principals:
current_principals.append(role_arn)
needs_update = True
logger.debug(f"Adding {role_type} role to data access policy: {role_arn}")
rule["Principal"] = current_principals
# Update policy if needed
if needs_update:
opensearch_client.update_access_policy(
name=data_policy_name,
type="data",
policy=json.dumps(current_policy),
policyVersion=policy_detail["accessPolicyDetail"]["policyVersion"]
)
logger.info(f"Updated data access policy to include roles")
else:
logger.debug("All roles already present in data access policy")
except Exception as update_error:
logger.warning(f"Could not update existing data access policy: {update_error}")
return {
"arn": collection_arn,
"endpoint": collection_endpoint
}
except Exception as e:
logger.debug(f"Error checking existing collections: {e}")
# Create encryption policy
enc_policy = {
"Rules": [
{
"ResourceType": "collection",
"Resource": [f"collection/{collection_name}"]
}
],
"AWSOwnedKey": True
}
try:
opensearch_client.create_security_policy(
name=enc_policy_name,
type="encryption",
description=f"opensearch encryption policy for {project_name}",
policy=json.dumps(enc_policy)
)
logger.debug(f"Created encryption policy: {enc_policy_name}")
except ClientError as e:
if e.response["Error"]["Code"] == "ConflictException":
logger.warning(f"Encryption policy already exists: {enc_policy_name}")
else:
logger.error(f"Failed to create encryption policy: {e}")
raise
# Create network policy
net_policy = [
{
"Rules": [
{
"ResourceType": "dashboard",
"Resource": [f"collection/{collection_name}"]
},
{
"ResourceType": "collection",
"Resource": [f"collection/{collection_name}"]
}
],
"AllowFromPublic": True
}
]
try:
opensearch_client.create_security_policy(
name=net_policy_name,
type="network",
description=f"opensearch network policy for {project_name}",
policy=json.dumps(net_policy)
)
logger.debug(f"Created network policy: {net_policy_name}")
except ClientError as e:
if e.response["Error"]["Code"] == "ConflictException":
logger.warning(f"Network policy already exists: {net_policy_name}")
else:
logger.error(f"Failed to create network policy: {e}")
raise
# Create data access policy
account_arn = f"arn:aws:iam::{account_id}:root"
principals = [account_arn]
# Add EC2 role to principals if provided
if ec2_role_arn:
principals.append(ec2_role_arn)
logger.debug(f"Adding EC2 role to data access policy: {ec2_role_arn}")
# Add Knowledge Base role to principals if provided
if knowledge_base_role_arn:
principals.append(knowledge_base_role_arn)
logger.debug(f"Adding Knowledge Base role to data access policy: {knowledge_base_role_arn}")
data_policy = [
{
"Rules": [
{
"Resource": [f"collection/{collection_name}"],
"Permission": [
"aoss:CreateCollectionItems",
"aoss:DeleteCollectionItems",
"aoss:UpdateCollectionItems",
"aoss:DescribeCollectionItems"
],
"ResourceType": "collection"
},
{
"Resource": [f"index/{collection_name}/*"],
"Permission": [
"aoss:CreateIndex",
"aoss:DeleteIndex",
"aoss:UpdateIndex",
"aoss:DescribeIndex",
"aoss:ReadDocument",
"aoss:WriteDocument"
],
"ResourceType": "index"
}
],
"Principal": principals
}
]
try:
opensearch_client.create_access_policy(
name=data_policy_name,
type="data",
policy=json.dumps(data_policy)
)
logger.debug(f"Created data access policy: {data_policy_name}")
except ClientError as e:
if e.response["Error"]["Code"] == "ConflictException":
logger.warning(f"Data access policy already exists: {data_policy_name}")
# Try to update existing policy to include roles
try:
# Get current policy version
policy_detail = opensearch_client.get_access_policy(
name=data_policy_name,
type="data"
)
current_policy = policy_detail["accessPolicyDetail"]["policy"]
# Check if roles are already in principals and update if needed
needs_update = False
roles_to_add = []
if ec2_role_arn:
roles_to_add.append(("EC2", ec2_role_arn))
if knowledge_base_role_arn:
roles_to_add.append(("Knowledge Base", knowledge_base_role_arn))
for rule in current_policy:
if "Principal" in rule:
current_principals = rule["Principal"]
if not isinstance(current_principals, list):
current_principals = [current_principals]
for role_type, role_arn in roles_to_add:
if role_arn and role_arn not in current_principals:
current_principals.append(role_arn)
needs_update = True
logger.debug(f"Adding {role_type} role to data access policy: {role_arn}")
rule["Principal"] = current_principals
# Update policy if needed
if needs_update:
opensearch_client.update_access_policy(
name=data_policy_name,
type="data",
policy=json.dumps(current_policy),
policyVersion=policy_detail["accessPolicyDetail"]["policyVersion"]
)
logger.info(f"Updated data access policy to include roles")
else:
logger.debug("All roles already present in data access policy")
except Exception as update_error:
logger.warning(f"Could not update existing data access policy: {update_error}")
if ec2_role_arn:
logger.warning(f"Please manually add EC2 role {ec2_role_arn} to the data access policy")
if knowledge_base_role_arn:
logger.warning(f"Please manually add Knowledge Base role {knowledge_base_role_arn} to the data access policy")
else:
logger.error(f"Failed to create data access policy: {e}")
raise
# Wait for policies to be ready
logger.debug("Waiting for policies to be ready...")
time.sleep(5)
# Create collection