aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.5k stars 3.84k forks source link

(autoscaling): Enhance Lambda permissions for EC2 Autoscaling Lifecycle Hooks #16758

Open SZubarev opened 2 years ago

SZubarev commented 2 years ago

I'm defining EC2 lifecycle hook with Lambda target using asg.addLifecycleHook() function.

asg.addLifecycleHook("terminateHook",{
      lifecycleTransition: LifecycleTransition.INSTANCE_TERMINATING,
      notificationTarget: new hooktargets.FunctionHook(scaledownlifecycleHookFn),
      defaultResult: autoscaling.DefaultResult.CONTINUE,
      heartbeatTimeout: cdk.Duration.seconds(120)
    })

When the Lambda executes it gets error: "not authorized to perform: autoscaling:CompleteLifecycleAction" when sends lifecycle completion message to autoscaling.

Proposed Solution

Automatically grant autoscaling:CompleteLifecycleAction permission to Lambda function set as a lifecycle hook target.

SZubarev commented 2 years ago

Checked the source code - looks like the permission "autoscaling:CompleteLifecycleAction" is granted to the target function but it didn't work until I explicitly assigned it to the function.

comcalvi commented 2 years ago

@SZubarev could you clarify what you mean by "explicitly assigning" it to the function? Where did you see that permission granted to the target function in the source code?

patrickmryan commented 1 year ago

I was looking for another issue when I stumbled across this one. I have encountered this situation and found a solution for my needs.

One key point to keep in mind is that the sequence of events when a scaling event occurs is not "ASG->lambda". The event will go through an intermediary (SNS, SQS, or EventBridge). So it may be trick/impossible for the synth step to infer what permissions need to get added to the target function.

Here's my solution -> https://github.com/patrickmryan/cdk-asg/blob/main/asg/asg_stack.py