Skip to content

aws-ec2: Instance L2 resource with cloud init creates non-unique launch template #34048

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

Closed
1 task
megakoresh opened this issue Apr 4, 2025 · 4 comments
Closed
1 task
Labels
@aws-cdk/aws-ec2 Related to Amazon Elastic Compute Cloud bug This issue is a bug. closing-soon This issue will automatically close in 4 days unless further comments are made. p3 response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.

Comments

@megakoresh
Copy link

megakoresh commented Apr 4, 2025

Describe the bug

A launch template is generated when you add cloudformationinit to an instance and this launch template is not unique. So if you deploy the same code with some different stack name, you get an error.

Regression Issue

  • Select this option if this issue appears to be a regression.

Last Known Working CDK Version

No response

Expected Behavior

I am able to create a new stack with different name from the same code and a new launch template is created with a unique name. Editing launch template name with this construct is impossible, so the construct isn't really usable if this way, despite it supposedly being valid use-case.

Current Behavior

QuestDb/Instance/LaunchTemplate (InstanceLaunchTemplateFB1C3D8B) Resource handler returned message: "Launch template name already in use. (Service: AmazonEC2; Status Code: 400; Error Code: InvalidLaunchTemplateName.AlreadyExistsException; 

Reproduction Steps

    const instance = new ec2.Instance(this, "Instance", {
      vpc: vpc,
      availabilityZone: vpc.availabilityZones[0],
      instanceType: instanceType,
      detailedMonitoring: true,
      machineImage: ec2.MachineImage.lookup({
        name: `questdb-${cfg.questdbVersion}*`,
      }),
      securityGroup,
      vpcSubnets: {
        subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
      },
      propagateTagsToVolumeOnCreation: true,
      requireImdsv2: true,
    });
    const volume = new ec2.Volume(this, `QuestdbVolume${hashFromString(`${cfg.questdbVersion}${cfg.snapshotId}`, 4)}`, {
      encrypted: true,
      availabilityZone: vpc.availabilityZones[0],
      snapshotId: cfg.snapshotId,
      size: cdk.Size.gibibytes(volumeSize),
    });
    instance.applyCloudFormationInit(
      ec2.CloudFormationInit.fromElements(
        ec2.InitFile.fromAsset("/opt/init/init.sh", path.join(__dirname, "init", "init.sh"), {
          mode: "000755",
        }),
        ec2.InitCommand.shellCommand("/opt/init/init.sh", {
          env: {
            VOLUME_ID: volume.volumeId,
            PG_USER_SECRET_NAME: secret.secretArn,
            STACK_NAME: this.stackName,
            RESOURCE_NAME: this.getLogicalId(instance.node.defaultChild as cdk.CfnElement),
          },
        }),
      ),
    );

Deploying the stack with new QuestdbStack(app, "QuestDB", {stackName: "some-other-name"}) will result in a name conflict.

Possible Solution

Generate a unique template name.

Additional Information/Context

The feature @aws-cdk/aws-ec2:uniqueImdsv2TemplateName is set to true.

CDK CLI Version

2.177.0

Framework Version

No response

Node.js Version

22.12

OS

Ubuntu 22.04

Language

TypeScript

Language Version

No response

Other information

Might be duplicate of #22695 but in that case it's a regression because the feature flag must have prevented this from happening.

@megakoresh megakoresh added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Apr 4, 2025
@github-actions github-actions bot added the @aws-cdk/aws-ec2 Related to Amazon Elastic Compute Cloud label Apr 4, 2025
@ykethan ykethan added investigating This issue is being investigated and/or work is in progress to resolve the issue. and removed needs-triage This issue or PR still needs to be triaged. labels Apr 5, 2025
@pahud pahud assigned pahud and unassigned ykethan Apr 7, 2025
@pahud
Copy link
Contributor

pahud commented Apr 7, 2025

HI @megakoresh

Did you deploy the two stacks like this?

// Instantiate the stack the first time with an explicit stack name
new Repro34048Stack(app, 'ReproStackInstance1', { // Using a slightly different ID for clarity in synth/diff
  stackName: 'repro-34048-instance-1', // Explicit stack name
  env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
  description: 'First deployment (explicit stackName) to reproduce issue 34048',
});

// Instantiate the stack the second time with the same ID but a different explicit stack name
new Repro34048Stack(app, 'ReproStackInstance2', { // Using a slightly different ID for clarity in synth/diff
  stackName: 'repro-34048-instance-2', // Different explicit stack name
  env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
  description: 'Second deployment (explicit stackName) to reproduce issue 34048',
});

stack.ts

import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';
import * as path from 'path'; // Needed for InitFile asset path

export class Repro34048Stack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Get the default VPC
    const vpc = ec2.Vpc.fromLookup(this, 'Vpc', { isDefault: true });

    // Create a basic security group
    const securityGroup = new ec2.SecurityGroup(this, 'InstanceSG', {
      vpc,
      allowAllOutbound: true,
    });
    // Allow SSH access (optional, for potential debugging)
    securityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), 'Allow SSH');

    // Create the EC2 instance
    const instance = new ec2.Instance(this, 'MyInstance', {
      vpc: vpc,
      instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
      // Use a recent Amazon Linux 2023 AMI
      machineImage: ec2.MachineImage.latestAmazonLinux2023(),
      securityGroup: securityGroup,
      // Ensure IMDSv2 is required - this triggers the problematic aspect
      requireImdsv2: true,
      // Select a subnet (e.g., public subnet)
      vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },
    });

    // Apply a minimal CloudFormation Init configuration
    // This is necessary along with requireImdsv2 to trigger the internal LT creation
    instance.applyCloudFormationInit(
      ec2.CloudFormationInit.fromElements(
        // Example: Create a dummy file
        ec2.InitFile.fromString('/tmp/hello.txt', 'Hello from cfn-init!'),
        // Example: Run a simple command
        ec2.InitCommand.shellCommand('echo "cfn-init executed" > /tmp/init-log.txt')
      ),
      // Default options are usually fine for reproduction
      {
         // Ensure fingerprinting is on (default) to associate init changes with UserData
         embedFingerprint: true,
         // Set a timeout for cfn-signal
         timeout: cdk.Duration.minutes(5),
      }
    );

    // Output the instance ID
    new cdk.CfnOutput(this, 'InstanceIdOutput', {
      value: instance.instanceId,
    });
  }
}

Looks like I can't reproduce this in 2.188.0. Can you share more details about it? And, can you try 2.188.0 and see if this issue still exists?

@pahud pahud added the p1 label Apr 7, 2025
@pahud pahud removed their assignment Apr 7, 2025
@pahud pahud added p3 response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. and removed p1 investigating This issue is being investigated and/or work is in progress to resolve the issue. labels Apr 7, 2025
Copy link

This issue has not received a response in a while. If you want to keep this issue open, please leave a comment below and auto-close will be canceled.

@github-actions github-actions bot added the closing-soon This issue will automatically close in 4 days unless further comments are made. label Apr 10, 2025
@megakoresh
Copy link
Author

Looks like I can't reproduce this in 2.188.0. Can you share more details about it? And, can you try 2.188.0 and see if this issue still exists?

yeah it seems that in 2.188.0 the issue is not there anymore so I will close this

Copy link

Comments on closed issues and PRs are hard for our team to see.
If you need help, please open a new issue that references this one.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 10, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
@aws-cdk/aws-ec2 Related to Amazon Elastic Compute Cloud bug This issue is a bug. closing-soon This issue will automatically close in 4 days unless further comments are made. p3 response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.
Projects
None yet
Development

No branches or pull requests

3 participants