amazon-web-servicesamazon-ec2aws-cdk

CDK deleted my EC2 instance, do you know why?


I have created a CDK proyect to deploy a simple EC2. I created it like this

// Create security group
    const publicEC2SG = new ec2.SecurityGroup(this, `EC2SG`, {
      vpc: vpc,
      allowAllOutbound: true,
      description: `Security Group for the eC2 server`,
      securityGroupName: `ec2-sg`,
    });
    publicEC2SG.addIngressRule(
      ec2.Peer.anyIpv4(),
      ec2.Port.tcp(22),
      "SSH from anywhere"
    );
    publicEC2SG.addIngressRule(
      ec2.Peer.anyIpv4(),
      ec2.Port.allIcmp(),
      "Ping from anywhere"
    ); 
    publicEC2SG.addIngressRule(
      ec2.Peer.anyIpv4(),
      ec2.Port.tcp(1883),
      "Mosquitto from anywhere"
    );

    // Launch EC2 instance in the public subnet (to be able to access it via SSH)
    let ec2_public = new ec2.Instance(this, "MyEC2", {
      vpc: vpc,
      vpcSubnets: {
        subnetType: ec2.SubnetType.PUBLIC,
      },
      instanceType: ec2.InstanceType.of(
        ec2.InstanceClass.T2,
        ec2.InstanceSize.MICRO
      ),
      role: roleEC2,
      machineImage: ec2.MachineImage.latestAmazonLinux2023(),
      instanceName: `public-ec2`,
      keyName: keyPair.keyName,
      securityGroup: publicEC2SG,
    });

    let eip = new ec2.CfnEIP(this, "server-ip", {
      instanceId: ec2_public.instanceId,
      tags: [new cdk.Tag("Name", `elastic-IP`)],
    });
    new cdk.CfnOutput(this, "my-ip", {
      value: ec2_public.instancePublicIp,
    });

I deployed it using cdk deploy and everything was created okey. I installed some programs and about a month later I needed to add port 1026 to the security group. So in the code above I added

   publicEC2SG.addIngressRule(
      ec2.Peer.anyIpv4(),
      ec2.Port.tcp(1026),
      "Personal port"
    );

And then did cdk deploy. But this time, the program deleted my previous machine and then created a new one (without anything installed). Why does this happen? In the message to accept the cdk deploy the only changes that appeared are the port added to the security group enter image description here

How can I avoid this in the future? Do I need to add something in my code?


Solution

  • Instead of using machineImage: ec2.MachineImage.latestAmazonLinux2023(), you should use a specific version, otherwise, if there is a new version available, your EC2 will use the new one, and will be recreated.

    Also, you should always do a cdk diff before a cdk deploy if it’s not already the case, it should have warned you for such behavior.

    And last thing, it’s not a good practice to do manual update in your EC2. You should always automate to avoid losing your updates and be able to scale easily. Make also sure to have retain on removal policy on your stateful resources (S3, DB, etc).