Skip to content

Commit 26a8254

Browse files
author
Yuriy Bezsonov
committed
Improve clean up
1 parent e9f4658 commit 26a8254

7 files changed

Lines changed: 240 additions & 107 deletions

File tree

.kiro/specs/infra/tasks.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,3 +920,10 @@
920920
- Updated Lambda function name to {prefix}-cfn-pre-delete-cleanup ✅
921921
- Updated WorkshopStack.java to use new class name ✅
922922
- _Requirements: 5.6_
923+
924+
- [x] 1300.4 Add GuardDuty security group cleanup
925+
- Added cleanup_guardduty_security_groups() function to Lambda ✅
926+
- Deletes security groups named GuardDutyManagedSecurityGroup-{vpc_id} ✅
927+
- Runs after VPC endpoints are deleted (security groups depend on endpoints) ✅
928+
- Added ec2:DescribeSecurityGroups and ec2:DeleteSecurityGroup permissions ✅
929+
- _Requirements: 5.6_

infra/cdk/src/main/java/sample/com/constructs/CfnPreDeleteCleanup.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,14 @@ public CfnPreDeleteCleanup(final Construct scope, final String id, final CfnPreD
5454
))
5555
.build();
5656

57-
// Add EC2 permissions for VPC endpoint operations
57+
// Add EC2 permissions for VPC endpoint and security group operations
5858
lambdaRole.addToPolicy(PolicyStatement.Builder.create()
5959
.effect(Effect.ALLOW)
6060
.actions(List.of(
6161
"ec2:DescribeVpcEndpoints",
62-
"ec2:DeleteVpcEndpoints"
62+
"ec2:DeleteVpcEndpoints",
63+
"ec2:DescribeSecurityGroups",
64+
"ec2:DeleteSecurityGroup"
6365
))
6466
.resources(List.of("*"))
6567
.build());

infra/cdk/src/main/resources/lambda/cfn-pre-delete-cleanup.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ def lambda_handler(event, context):
1010
"""
1111
Custom Resource handler to cleanup resources before stack deletion.
1212
- GuardDuty VPC endpoints that block VPC deletion
13+
- GuardDuty managed security groups
1314
- CloudWatch log groups with workshop- or unicornstore- prefix
1415
- S3 bucket contents for workshop- buckets
1516
"""
@@ -31,6 +32,9 @@ def lambda_handler(event, context):
3132
if endpoint_ids:
3233
wait_for_deletion(endpoint_ids, max_wait=300)
3334

35+
# Delete GuardDuty security groups (after endpoints are deleted)
36+
cleanup_guardduty_security_groups(vpc_id)
37+
3438
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
3539
except Exception as e:
3640
print(f"Error: {e}")
@@ -64,6 +68,42 @@ def start_guardduty_endpoint_deletion(vpc_id):
6468

6569
return endpoint_ids
6670

71+
def cleanup_guardduty_security_groups(vpc_id):
72+
"""Delete GuardDuty managed security groups for the VPC."""
73+
if not vpc_id:
74+
print("No VPC ID provided, skipping security group cleanup")
75+
return
76+
77+
try:
78+
# Find GuardDuty managed security groups by name pattern
79+
response = ec2.describe_security_groups(
80+
Filters=[
81+
{'Name': 'vpc-id', 'Values': [vpc_id]},
82+
{'Name': 'group-name', 'Values': [f'GuardDutyManagedSecurityGroup-{vpc_id}']}
83+
]
84+
)
85+
86+
security_groups = response.get('SecurityGroups', [])
87+
88+
if not security_groups:
89+
print("No GuardDuty security groups found")
90+
return
91+
92+
for sg in security_groups:
93+
sg_id = sg['GroupId']
94+
sg_name = sg['GroupName']
95+
print(f"Deleting GuardDuty security group: {sg_name} ({sg_id})")
96+
try:
97+
ec2.delete_security_group(GroupId=sg_id)
98+
print(f"Deleted security group: {sg_id}")
99+
except Exception as e:
100+
print(f"Error deleting security group {sg_id}: {e}")
101+
102+
except Exception as e:
103+
print(f"Error listing GuardDuty security groups: {e}")
104+
105+
print("GuardDuty security group cleanup completed")
106+
67107
def cleanup_cloudwatch_logs():
68108
"""Delete CloudWatch log groups with workshop- or unicornstore- prefix."""
69109
prefixes = ['workshop-', 'unicornstore-', '/aws/lambda/workshop-', '/aws/lambda/unicornstore-']

infra/cfn/java-ai-agents-stack.yaml

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -757,30 +757,12 @@ Resources:
757757
Fn::GetAtt:
758758
- IdeInstanceLauncherFunction803C5A2A
759759
- Arn
760-
InstanceName: ide
761760
IamInstanceProfileArn:
762761
Fn::GetAtt:
763762
- IdeInstanceProfile61B92038
764763
- Arn
765-
VolumeSize: "50"
766-
SubnetIds:
767-
Fn::Join:
768-
- ""
769-
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
770-
- ","
771-
- Ref: VpcPublicSubnet2SubnetA811849C
772-
SecurityGroupIds:
773-
Fn::Join:
774-
- ""
775-
- - Fn::GetAtt:
776-
- IdeSecurityGroup73B02454
777-
- GroupId
778-
- ","
779-
- Fn::GetAtt:
780-
- IdeInternalSecurityGroupB0A5D76B
781-
- GroupId
782-
ImageId:
783-
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestal2023amikernel61arm64C96584B6F00A464EAD1953AFF4B05118Parameter
764+
InstanceName: ide
765+
InstanceTypes: m7g.xlarge,m6g.xlarge,c7g.xlarge,t4g.xlarge
784766
UserData:
785767
Fn::Base64:
786768
Fn::Join:
@@ -917,7 +899,25 @@ Resources:
917899
"
918900
exit 1
919901
fi
920-
InstanceTypes: m7g.xlarge,m6g.xlarge,c7g.xlarge,t4g.xlarge
902+
ImageId:
903+
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestal2023amikernel61arm64C96584B6F00A464EAD1953AFF4B05118Parameter
904+
SecurityGroupIds:
905+
Fn::Join:
906+
- ""
907+
- - Fn::GetAtt:
908+
- IdeSecurityGroup73B02454
909+
- GroupId
910+
- ","
911+
- Fn::GetAtt:
912+
- IdeInternalSecurityGroupB0A5D76B
913+
- GroupId
914+
SubnetIds:
915+
Fn::Join:
916+
- ""
917+
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
918+
- ","
919+
- Ref: VpcPublicSubnet2SubnetA811849C
920+
VolumeSize: "50"
921921
UpdateReplacePolicy: Delete
922922
DeletionPolicy: Delete
923923
IdeEipAssociationDFF81215:

infra/cfn/java-on-amazon-eks-stack.yaml

Lines changed: 77 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,25 @@ Resources:
777777
Fn::GetAtt:
778778
- IdeInstanceLauncherFunction803C5A2A
779779
- Arn
780+
VolumeSize: "50"
781+
SubnetIds:
782+
Fn::Join:
783+
- ""
784+
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
785+
- ","
786+
- Ref: VpcPublicSubnet2SubnetA811849C
787+
SecurityGroupIds:
788+
Fn::Join:
789+
- ""
790+
- - Fn::GetAtt:
791+
- IdeSecurityGroup73B02454
792+
- GroupId
793+
- ","
794+
- Fn::GetAtt:
795+
- IdeInternalSecurityGroupB0A5D76B
796+
- GroupId
797+
ImageId:
798+
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestal2023amikernel61arm64C96584B6F00A464EAD1953AFF4B05118Parameter
780799
UserData:
781800
Fn::Base64:
782801
Fn::Join:
@@ -913,31 +932,12 @@ Resources:
913932
"
914933
exit 1
915934
fi
916-
ImageId:
917-
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestal2023amikernel61arm64C96584B6F00A464EAD1953AFF4B05118Parameter
918-
SecurityGroupIds:
919-
Fn::Join:
920-
- ""
921-
- - Fn::GetAtt:
922-
- IdeSecurityGroup73B02454
923-
- GroupId
924-
- ","
925-
- Fn::GetAtt:
926-
- IdeInternalSecurityGroupB0A5D76B
927-
- GroupId
928-
SubnetIds:
929-
Fn::Join:
930-
- ""
931-
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
932-
- ","
933-
- Ref: VpcPublicSubnet2SubnetA811849C
934-
VolumeSize: "50"
935+
InstanceTypes: m7g.xlarge,m6g.xlarge,c7g.xlarge,t4g.xlarge
936+
InstanceName: ide
935937
IamInstanceProfileArn:
936938
Fn::GetAtt:
937939
- IdeInstanceProfile61B92038
938940
- Arn
939-
InstanceName: ide
940-
InstanceTypes: m7g.xlarge,m6g.xlarge,c7g.xlarge,t4g.xlarge
941941
UpdateReplacePolicy: Delete
942942
DeletionPolicy: Delete
943943
IdeEipAssociationDFF81215:
@@ -1316,12 +1316,12 @@ Resources:
13161316
Environment:
13171317
ComputeType: BUILD_GENERAL1_MEDIUM
13181318
EnvironmentVariables:
1319-
- Name: TEMPLATE_TYPE
1320-
Type: PLAINTEXT
1321-
Value: java-on-amazon-eks
13221319
- Name: GIT_BRANCH
13231320
Type: PLAINTEXT
13241321
Value: new-ws-infra
1322+
- Name: TEMPLATE_TYPE
1323+
Type: PLAINTEXT
1324+
Value: java-on-amazon-eks
13251325
Image: aws/codebuild/amazonlinux2-x86_64-standard:5.0
13261326
ImagePullCredentialsType: CODEBUILD
13271327
PrivilegedMode: false
@@ -1526,12 +1526,12 @@ Resources:
15261526
Description: workshop-setup build complete
15271527
EventPattern:
15281528
detail:
1529-
project-name:
1530-
- Ref: CodeBuildProjectA0FF5539
15311529
build-status:
15321530
- SUCCEEDED
15331531
- FAILED
15341532
- STOPPED
1533+
project-name:
1534+
- Ref: CodeBuildProjectA0FF5539
15351535
detail-type:
15361536
- CodeBuild Build State Change
15371537
source:
@@ -1563,13 +1563,13 @@ Resources:
15631563
Fn::GetAtt:
15641564
- CodeBuildStartLambdaFunction8349284F
15651565
- Arn
1566+
ProjectName:
1567+
Ref: CodeBuildProjectA0FF5539
15661568
CodeBuildIamRoleArn:
15671569
Fn::GetAtt:
15681570
- CodeBuildRoleE9A44575
15691571
- Arn
1570-
ProjectName:
1571-
Ref: CodeBuildProjectA0FF5539
1572-
ContentHash: "1766246265432"
1572+
ContentHash: "1766247102819"
15731573
DependsOn:
15741574
- CodeBuildCompleteRuleAllowEventRuleWorkshopStackCodeBuildReportLambdaFunctionD77C60919E0B0C89
15751575
- CodeBuildCompleteRuleEE9277E8
@@ -1921,7 +1921,7 @@ Resources:
19211921
- Ref: AWS::AccountId
19221922
- "-"
19231923
- Ref: AWS::Region
1924-
- "-20251220165745"
1924+
- "-20251220171143"
19251925
PublicAccessBlockConfiguration:
19261926
BlockPublicAcls: true
19271927
BlockPublicPolicy: true
@@ -2232,15 +2232,15 @@ Resources:
22322232
}
22332233
Environment:
22342234
Variables:
2235-
SECRET_NAME: workshop-ide-password
22362235
S3_BUCKET_NAME:
22372236
Ref: WorkshopBucketFD5BC43F
2237+
SECRET_NAME: workshop-ide-password
2238+
KUBERNETES_AUTH_TYPE: aws
2239+
APP_LABEL: unicorn-store-spring
2240+
K8S_NAMESPACE: unicorn-store-spring
2241+
S3_THREAD_DUMPS_PREFIX: thread-dumps/
22382242
EKS_CLUSTER_NAME:
22392243
Ref: EksClusterB2BDED5B
2240-
S3_THREAD_DUMPS_PREFIX: thread-dumps/
2241-
K8S_NAMESPACE: unicorn-store-spring
2242-
APP_LABEL: unicorn-store-spring
2243-
KUBERNETES_AUTH_TYPE: aws
22442244
FunctionName: workshop-thread-dump-lambda
22452245
Handler: index.lambda_handler
22462246
MemorySize: 512
@@ -2845,7 +2845,9 @@ Resources:
28452845
PolicyDocument:
28462846
Statement:
28472847
- Action:
2848+
- ec2:DeleteSecurityGroup
28482849
- ec2:DeleteVpcEndpoints
2850+
- ec2:DescribeSecurityGroups
28492851
- ec2:DescribeVpcEndpoints
28502852
- logs:DeleteLogGroup
28512853
- logs:DescribeLogGroups
@@ -2877,6 +2879,7 @@ Resources:
28772879
"""
28782880
Custom Resource handler to cleanup resources before stack deletion.
28792881
- GuardDuty VPC endpoints that block VPC deletion
2882+
- GuardDuty managed security groups
28802883
- CloudWatch log groups with workshop- or unicornstore- prefix
28812884
- S3 bucket contents for workshop- buckets
28822885
"""
@@ -2898,6 +2901,9 @@ Resources:
28982901
if endpoint_ids:
28992902
wait_for_deletion(endpoint_ids, max_wait=300)
29002903
2904+
# Delete GuardDuty security groups (after endpoints are deleted)
2905+
cleanup_guardduty_security_groups(vpc_id)
2906+
29012907
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
29022908
except Exception as e:
29032909
print(f"Error: {e}")
@@ -2931,6 +2937,42 @@ Resources:
29312937
29322938
return endpoint_ids
29332939
2940+
def cleanup_guardduty_security_groups(vpc_id):
2941+
"""Delete GuardDuty managed security groups for the VPC."""
2942+
if not vpc_id:
2943+
print("No VPC ID provided, skipping security group cleanup")
2944+
return
2945+
2946+
try:
2947+
# Find GuardDuty managed security groups by name pattern
2948+
response = ec2.describe_security_groups(
2949+
Filters=[
2950+
{'Name': 'vpc-id', 'Values': [vpc_id]},
2951+
{'Name': 'group-name', 'Values': [f'GuardDutyManagedSecurityGroup-{vpc_id}']}
2952+
]
2953+
)
2954+
2955+
security_groups = response.get('SecurityGroups', [])
2956+
2957+
if not security_groups:
2958+
print("No GuardDuty security groups found")
2959+
return
2960+
2961+
for sg in security_groups:
2962+
sg_id = sg['GroupId']
2963+
sg_name = sg['GroupName']
2964+
print(f"Deleting GuardDuty security group: {sg_name} ({sg_id})")
2965+
try:
2966+
ec2.delete_security_group(GroupId=sg_id)
2967+
print(f"Deleted security group: {sg_id}")
2968+
except Exception as e:
2969+
print(f"Error deleting security group {sg_id}: {e}")
2970+
2971+
except Exception as e:
2972+
print(f"Error listing GuardDuty security groups: {e}")
2973+
2974+
print("GuardDuty security group cleanup completed")
2975+
29342976
def cleanup_cloudwatch_logs():
29352977
"""Delete CloudWatch log groups with workshop- or unicornstore- prefix."""
29362978
prefixes = ['workshop-', 'unicornstore-', '/aws/lambda/workshop-', '/aws/lambda/unicornstore-']

0 commit comments

Comments
 (0)