Skip to content
New issue

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

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

Already on GitHub? # to your account

(aws-autoscaling): AutoScalingGroup.requireImdsv2 throws error with LaunchTemplates #27586

Closed
patlougheed opened this issue Oct 17, 2023 · 6 comments · Fixed by #27648 or #32220
Closed
Labels
@aws-cdk/aws-autoscaling Related to Amazon EC2 Auto Scaling bug This issue is a bug. effort/small Small work item – less than a day of effort p1

Comments

@patlougheed
Copy link

Describe the bug

When configuring an AutoScalingGroup with requireImdsv2 set to true and the generateLaunchTemplateInsteadOfLaunchConfig context flag set to true, cdk synth throws an error:

RuntimeError: TypeError: Cannot read properties of undefined (reading 'metadataOptions')

Expected Behavior

No error; launch template should have LaunchTemplateData.MetadataOptions.HttpTokens set to "required" in resulting CloudFormation output.

Current Behavior

cdk synth yields:

cdk synth
jsii.errors.JavaScriptError:
  @jsii/kernel.RuntimeError: TypeError: Cannot read properties of undefined (reading 'metadataOptions')
      at Kernel._Kernel_ensureSync (/private/var/folders/xw/cr5bdphj6v329dhsnsp7g4cm0000gn/T/tmppv5ogwr4/lib/program.js:10487:23)
      at Kernel.invoke (/private/var/folders/xw/cr5bdphj6v329dhsnsp7g4cm0000gn/T/tmppv5ogwr4/lib/program.js:9851:102)
      at KernelHost.processRequest (/private/var/folders/xw/cr5bdphj6v329dhsnsp7g4cm0000gn/T/tmppv5ogwr4/lib/program.js:11691:36)
      at KernelHost.run (/private/var/folders/xw/cr5bdphj6v329dhsnsp7g4cm0000gn/T/tmppv5ogwr4/lib/program.js:11651:22)
      at Immediate._onImmediate (/private/var/folders/xw/cr5bdphj6v329dhsnsp7g4cm0000gn/T/tmppv5ogwr4/lib/program.js:11652:46)
      at process.processImmediate (node:internal/timers:478:21)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".../app.py", line 28, in <module>
    app.synth()
  File ".../.venv/lib/python3.10/site-packages/aws_cdk/__init__.py", line 21202, in synth
    return typing.cast(_CloudAssembly_c693643e, jsii.invoke(self, "synth", [options]))
  File "....venv/lib/python3.10/site-packages/jsii/_kernel/__init__.py", line 149, in wrapped
    return _recursize_dereference(kernel, fn(kernel, *args, **kwargs))
  File ".../.venv/lib/python3.10/site-packages/jsii/_kernel/__init__.py", line 399, in invoke
    response = self.provider.invoke(
  File ".../.venv/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 380, in invoke
    return self._process.send(request, InvokeResponse)
  File ".../.venv/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 342, in send
    raise RuntimeError(resp.error) from JavaScriptError(resp.stack)
RuntimeError: TypeError: Cannot read properties of undefined (reading 'metadataOptions')

Subprocess exited with error 1

Reproduction Steps

In stack.py:

from aws_cdk import (
    aws_autoscaling as autoscaling,
    aws_ec2 as ec2,
    Stack
)
from constructs import Construct


class TroubleshootingStack(Stack):
    def __init__(self, scope: Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = ec2.Vpc(self, 'Vpc')
        autoscaling.AutoScalingGroup(self, 'AutoscalingGroup', vpc=vpc, require_imdsv2=True)

In cdk.json:

{
  "app": "python3 app.py",
  "context": {
    "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true
  }
}

Then run cdk synth.

Possible Solution

aws-autoscaling/lib/aspects/require-imdsv2-aspect.ts appears to target LaunchConfigurations only, not LaunchTemplates.

It similar aspect in (aws-ec2)[https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/aws-ec2/lib/aspects/require-imdsv2-aspect.ts] has similar code that appears to support LaunchTemplates.

Additional Information/Context

No response

CDK CLI Version

2.101.1

Framework Version

2.101.1

Node.js Version

v20.7.0

OS

MacOS 14

Language

Python

Language Version

Python 3.10.9

Other information

No response

@patlougheed patlougheed added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Oct 17, 2023
@github-actions github-actions bot added the @aws-cdk/aws-autoscaling Related to Amazon EC2 Auto Scaling label Oct 17, 2023
@khushail khushail 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 Oct 18, 2023
@khushail
Copy link
Contributor

khushail commented Oct 20, 2023

Hi @patlougheed , thanks for reaching out. I tried to reproduce the error with this updated code -

        asg = autoscaling.AutoScalingGroup(
            self, "DefaultAutoScalingGroup",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ecs.EcsOptimizedImage.amazon_linux2(),
            vpc=vpc,
            require_imdsv2= True,
        )

I can confirm the error. Here is a similiar non-responsive issue created in the past as well. Marking this as P1.

@khushail khushail added p1 effort/small Small work item – less than a day of effort and removed investigating This issue is being investigated and/or work is in progress to resolve the issue. labels Oct 20, 2023
@mergify mergify bot closed this as completed in #27648 Oct 26, 2023
mergify bot pushed a commit that referenced this issue Oct 26, 2023
…unchTemplates (#27648)

This PR fixes the bug that AutoScalingGroup.requireImdsv2 throws error with LaunchTemplates.

This handles `LaunchTemplate` in `AutoScalingGroupRequireImdsv2Aspect` when a feature flag `AUTOSCALING_GENERATE_LAUNCH_TEMPLATE` is true.

Closes #27586.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
@github-actions
Copy link

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please either tag a team member or open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

mrgrain pushed a commit that referenced this issue Nov 1, 2023
…unchTemplates (#27648)

This PR fixes the bug that AutoScalingGroup.requireImdsv2 throws error with LaunchTemplates.

This handles `LaunchTemplate` in `AutoScalingGroupRequireImdsv2Aspect` when a feature flag `AUTOSCALING_GENERATE_LAUNCH_TEMPLATE` is true.

Closes #27586.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
@dendle
Copy link

dendle commented Sep 11, 2024

Hi folks - this problem appears to also exist when using A LaunchTemplate with a MixedInstancesPolicy and RequireImdsv2=true

@dendle
Copy link

dendle commented Sep 11, 2024

Going to see if I can get a PR on the go for the above issue

@thorbenw
Copy link

I also get the above error, but was able to solve it by setting RequireImdsv2 only on the launch template, but not on the auto scaling group itself.
Maybe the RequireImdsv2 property should just receive a few changes in packages/aws-cdk-lib/aws-autoscaling/lib/auto-scaling-group.ts, like

  • An annotation like some other properties (e.g. SecurityGroup, Role, etc.) have, saying * 'launchTemplate' and 'mixedInstancesPolicy' must not be specified when this property is specified
  • A check included in the verifyNoLaunchConfigPropIsGiven() method to give a more meaningful error message on synth

@shinebleu
Copy link
Contributor

Made a pull request adding a check for requireImdsv2 in verifyNoLaunchConfigPropIsGiven as suggested above.

mergify bot pushed a commit that referenced this issue Dec 9, 2024
…e or mixedInstancesPolicy throws unclear error (#32220)

### Issue #27586

Fixes #27586

The above issue is already marked as closed, but there is some discussion in it about an additional edge case that this pull request fixes.

### Reason for this change

When defining an AutoScalingGroup with both the `requireImdsv2` prop and the `launchTemplate` prop, the error message is not clear about the problem.

```
    // example asg definition
    const asg = new AutoScalingGroup(this, "myasg", {
      vpc,
      launchTemplate: lt,
      requireImdsv2: true,
    });
```

```
TypeError: Cannot read properties of undefined (reading 'node')
    at AutoScalingGroupRequireImdsv2Aspect.visit (~/git/cdkApp2/node_modules/aws-cdk-lib/aws-autoscaling/lib/aspects/require-imdsv2-aspect.js:1:715)
    at recurse (~/git/cdkApp2/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:2:2236)
    at recurse (~/git/cdkApp2/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:2:2600)
    at recurse (~/git/cdkApp2/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:2:2600)
    at invokeAspects (~/git/cdkApp2/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:2:1860)
    at synthesize (~/git/cdkApp2/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:1:1473)
    at App.synth (~/git/cdkApp2/node_modules/aws-cdk-lib/core/lib/stage.js:1:2382)
    at process.<anonymous> (~/git/cdkApp2/node_modules/aws-cdk-lib/core/lib/app.js:1:1767)
    at Object.onceWrapper (node:events:632:26)
    at process.emit (node:events:517:28)
```

It is not clear from the error that `requireImdsv2` should be set in the provided launchTemplate itself rather than the AutoScalingGroup.

The error occurs because setting `requireImdsv2` on the AutoScalingGroup adds the aspect AutoScalingGroupRequireImdsv2Aspect to it, which expects there to be a child node called either `'LaunchConfig'` or `'LaunchTemplate'` depending on a feature flag. This child node is only set in the AutoScalingGroup when neither `launchTemplate` nor `mixedInstancesPolicy` props are provided.

### Description of changes

Add the `requireImdsv2` prop to the `verifyNoLaunchConfigPropIsGiven` method, which throws errors when certains props are set at the same time as `launchTemplate` or `mixedInstancesPolicy`.

### Description of how you validated changes

- Added a unit test
- Confirmed the new error message works in a sample cdk app

```
Error: Setting 'requireImdsv2' must not be set when 'launchTemplate' or 'mixedInstancesPolicy' is set
    at AutoScalingGroup.verifyNoLaunchConfigPropIsGiven (~/git/aws-cdk/packages/aws-cdk-lib/aws-autoscaling/lib/auto-scaling-group.ts:1762:13)
    at new AutoScalingGroup (~/git/aws-cdk/packages/aws-cdk-lib/aws-autoscaling/lib/auto-scaling-group.ts:1333:12)
    at new CdkAppStack (~/git/cdkApp/lib/cdk_app-stack.ts:31:17)
    at Object.<anonymous> (~/git/cdkApp/bin/cdk_app.ts:6:1)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module.m._compile (~/git/cdkApp/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Object.require.extensions.<computed> [as .ts] (~/git/cdkApp/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Function.Module._load (node:internal/modules/cjs/loader:960:12)
```

### Checklist
- [X] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md)

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
@aws-cdk/aws-autoscaling Related to Amazon EC2 Auto Scaling bug This issue is a bug. effort/small Small work item – less than a day of effort p1
Projects
None yet
5 participants