在EC2终止时调用脚本 [英] Invoke a script on EC2 termination

查看:133
本文介绍了在EC2终止时调用脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AWS自动伸缩扩展事件期间,我必须采取某些措施.ec2实例应该能够将一些日志和报告保存到S3存储桶中.这可能需要5到15分钟.

I have to take certain actions during AWS autoscaling scale-in event.The ec2 instance should be able to save some logs and reports to S3 bucket. This can take anywhere between 5 to 15 mins.

我已经有一个终止时会调用的脚本:

I already have a script that gets called on termination:

ln -s /etc/ec2-termination /etc/rc0.d/S01ec2-termination

但是脚本在5分钟内突然结束.我正在考虑利用AWS LifeCycle挂钩来延长EC2寿命. 关于以类似于用户数据脚本的方式调用脚本的文档尚不清楚.

However the script ends abruptly within 5 mins. I am looking at leveraging AWS LifeCycle hooks to extend the EC2 lifetime. The documentation is not clear on invoking a script in a way similar to user-data script.

有多种使用AWS lambda或SNS接收通知的方法.这可以潜在地用于通知ec2.

There are ways of using AWS lambda or SNS to receive notification. This can be potentially used to inform the ec2.

但是,我想知道是否有一个更简单的解决此问题的方法.有没有一种方法可以使用在扩展事件中调用的Lifecycle挂钩来注册脚本.

But, I would like to know if there is a simpler solution to this problem. Is there a way to register a script with Lifecycle hooks that gets called on a scale-in event.

推荐答案

否.

实例终止的事实在AWS基础架构中进行管理. Auto Scaling无法访问EC2实例以触发任何内容.

The fact that the instance is being terminated is managed within the AWS infrastructure. Auto Scaling does not have the ability to reach "into" the EC2 instance to trigger anything.

相反,您需要在实例上编写一些代码,以检查实例是否处于终止状态,然后采取适当的措施.

Instead, you would need to write some code on the instance that checks whether the instance is in the termination state and then takes appropriate action.

一个例子可能是:

  • 生命周期挂钩通过Amazon SNS发送通知
  • Amazon SNS 触发AWS Lambda函数
  • Lambda函数可以向实例添加标签(例如Termination = Yes)
  • 每15秒钟触发一次EC2实例上的脚本,以检查与该EC2实例(在其上运行)相关联的标签.如果找到标签,则会触发关机过程.
  • The Lifecycle Hook sends a notification via Amazon SNS
  • Amazon SNS triggers an AWS Lambda function
  • The Lambda function could add a tag to the instance (eg Terminating = Yes)
  • A script on the EC2 instance is triggered every 15 seconds to check the tags associated with the EC2 instance (on which it is running). If it finds the tag, it triggers the shutdown process.

(请注意,脚本在关闭过程中不会再次触发,否则可能会尝试每15秒执行一次关闭过程!)

(Be careful that the script doesn't trigger again during the shutdown process otherwise it might try performing the shutdown process every 15 seconds!)

或者,将关闭信息存储在Systems Manager参数存储或数据库中,但是使用标记"似乎具有很好的可伸缩性!

Alternatively, store the shutdown information in the Systems Manager Parameter Store or a database, but using Tags seems nicely scalable!

更新版本:

感谢raevilman的想法:

Thanks to raevilman for the idea:

  • The Lifecycle Hook sends a notification via Amazon SNS
  • Amazon SNS triggers an AWS Lambda function
  • The Lambda function calls the AWS Systems Manager Run Command to trigger code on the instance

简单得多!

这篇关于在EC2终止时调用脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆