Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EC2 re-creation on CDK deploy

All our stack resources run inside a VPC, so in order to access them we use a Bastion Host, a simple EC2 instance to create an SSH tunnel into the VPC.

We then added our SSH keys to the host, but it seems the EC2 gets replaced by a new one from time to time when deploying our CDK stack. We then have to re-add our SSH keys each time.

Is there a way to not re-create the EC2 instance?

Our code:

export default class FooStack extends Stack {
    constructor(scope: App, id: string, props?: StackProps) {
        super(scope, id, props);

        const vpc = this.createVPC();
        const bastionSecurityGroup = this.createBastionSecurityGroup(vpc);
        this.createBastionHost(bastionSecurityGroup, vpc);
    }

    private createVPC() {
        const vpc = new Vpc(this, 'Vpc', { natGateways: 1 });
        return vpc;
    }

    private createBastionSecurityGroup(vpc: Vpc) {
        const bastionSecurityGroup = new SecurityGroup(this, 'BastionSecurityGroup', { vpc, allowAllOutbound: true });
        bastionSecurityGroup.connections.allowFrom(
            bastionSecurityGroup,
            Port.allTraffic(),
            'Allow inbound traffic to the Bastion Host from its security group',
        );
        bastionSecurityGroup.addIngressRule(
            Peer.anyIpv4(),
            Port.tcp(22),
            'Allow inbound traffic to the Bastion Host on port 22.',
        );
        return bastionSecurityGroup;
    }

    private createBastionHost(securityGroup: SecurityGroup, vpc: Vpc) {
        new BastionHostLinux(this, 'BastionHost', {
            vpc,
            instanceType: InstanceType.of(InstanceClass.T3, InstanceSize.NANO),
            securityGroup,
            subnetSelection: vpc.selectSubnets({ subnets: [vpc.publicSubnets[0]] }),
        });
    }
}

like image 442
Dries Hooghe Avatar asked May 05 '26 22:05

Dries Hooghe


1 Answers

The problem was that I didn't specify the AMI (Amazon Machine Image). As a result, every time a new version of the image was released, the instance would be recreated when deployed.

like image 81
Dries Hooghe Avatar answered May 10 '26 23:05

Dries Hooghe