Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix to successfully destroy CDK due to VPC peering #1085

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions labs/unicorn-store/delete-vpc-peering.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#bin/sh

UNICORN_VPC_ID=$(aws cloudformation describe-stacks --stack-name UnicornStoreInfrastructure --query 'Stacks[0].Outputs[?OutputKey==`UnicornStoreVpcId`].OutputValue' --output text)

VPC_PEERING_CONNECTION_ID=$(aws ec2 describe-vpc-peering-connections --filters "Name=accepter-vpc-info.vpc-id,Values=$UNICORN_VPC_ID" --query 'VpcPeeringConnections[0].VpcPeeringConnectionId' --output text)

aws ec2 delete-vpc-peering-connection --vpc-peering-connection-id $VPC_PEERING_CONNECTION_ID
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
import software.amazon.awscdk.services.events.EventBus;
import software.amazon.awscdk.services.rds.*;
import software.constructs.Construct;
import software.amazon.awscdk.Aspects;
import software.amazon.awscdk.IAspect;
import software.constructs.IConstruct;

import java.io.IOException;
import java.util.List;

public class InfrastructureStack extends Stack {
Expand Down Expand Up @@ -36,9 +40,10 @@ public InfrastructureStack(final Construct scope, final String id, final StackPr
createEventBridgeVpcEndpoint();
createDynamoDBVpcEndpoint();
new DatabaseSetupConstruct(this, "UnicornDatabaseConstruct");

Aspects.of(this).add(new PreDestroyHook());
}


private EventBus createEventBus() {
return EventBus.Builder.create(this, "UnicornEventBus")
.eventBusName("unicorns")
Expand Down Expand Up @@ -136,4 +141,25 @@ private IGatewayVpcEndpoint createDynamoDBVpcEndpoint() {
.build();
}

private void runCustomScript(String scriptPath) {
try {
Process process = Runtime.getRuntime().exec(scriptPath);
int exitCode = process.waitFor();
if (exitCode != 0) {
System.err.println("Error running custom script. Exit code: " + exitCode);
}
} catch (IOException | InterruptedException e) {
System.err.println("Error running custom script: " + e.getMessage());
}
}

class PreDestroyHook implements IAspect {
@Override
public void visit(IConstruct node) {
if (node instanceof software.amazon.awscdk.Stack) {
runCustomScript("/home/ec2-user/environment/aws-lambda-java-workshop/labs/unicorn-store/delete-vpc-peering.sh");
}
}
}

}
Loading