【问题标题】:Notification from AWS based on instances status and instances durationAWS 基于实例状态和实例持续时间的通知
【发布时间】:2020-08-18 13:55:14
【问题描述】:

其实我想减少 AWS 账单。我在我的项目中使用了一些实例。我希望在我的登录电子邮件 ID 上的特定时间段(每 3/4 小时)后收到通知,并在特定时间段内关闭。那么,我该怎么做呢?

if current time - instance start time >= 3 hr (send a mail)
if current time - instance start time >= 4 hr (send a mail)
if current time - instance start time >= 5 hr (shut down that instance)

【问题讨论】:

  • 没有内置功能来执行您的请求,但您可以使用 AWS Lambda 函数自行编写代码。另见:Use Amazon CloudWatch to Detect and Shut Down Unused Amazon EC2 Instances
  • 谢谢你,我已经编辑了,你可以看看更好的理解。
  • 将 lambda 函数的目标添加到 SNS 时出现错误。 Your function's execution role doesn't have permission to send result to the destination. By clicking save we'll attempt to add permission to the role for you. 。我给出了两个策略(EC2FullAccess 和 SNSFullAccess)。为什么显示你没有权限?它还需要哪些政策?
  • 为什么要为 Lambda 函数定义目标?
  • 仅供参考,根据您的要求,我是 writing a few Stopinators。 Stopinator Type 2 处理“停止后”,但还没有通知。

标签: amazon-web-services amazon-ec2 aws-lambda amazon-cloudwatch amazon-sns


【解决方案1】:

对于您的用例,我编写了一个 Stopinator,它可以在给定的持续时间后停止/终止实例。

此外,它可以在给定的运行时间后向 Amazon SNS 主题发送通知。

见:GutHub: Simple Lambda Stopinator: Type 2

通过标签控制:

标签名称(按优先顺序):

  • Terminate-After: 终止实例
  • Stop-After:停止实例
  • Notify-After:如果仍在运行,发送 SNS 通知 (对于多个通知,请使用Notify-After1Notify-After2 等)

标签值:表示跑步时长(例如'30m'、'1.5h'、24h')

使用 Amazon CloudWatch Events 安排 Lambda 函数定期运行(例如每 5 分钟一次)。

更多详情请见:Simple EC2 Stopinator in Lambda - DEV Community

【讨论】:

    【解决方案2】:

    通常您可以设置 CloudWatch Schedule Expressions for Rules,它会定期触发您需要的操作。您可以通过在 CloudWatch Event 规则中定义 Cron Expressions 来设置周期性任务。

    这些操作可以是 SNS 向您发送电子邮件,或执行 EC2 StopInstances API call 以自动停止您的实例。

    【讨论】:

      【解决方案3】:

      您可以通过设置云监视事件并使用 cron 表达式安排该事件来做到这一点。转到:AWS控制台-> cloudwatch->事件->规则->创建规则->计划->输入您想要的cron表达式->目标(您将执行任务的lambda函数)。 在您的 lambda 函数中,您可以使用

      ec2_client = boto3.client('ec2')
      response = ec2_client.describe_instance_status()
      #response can give detail about other and particular instance also
      instance_status_details = response['InstanceStatuses'][0]['InstanceStatus']['Details']
      #there is impairedSince parameter (inside instance_status_detail) to figure out when you launched this instance
      #take from this link  https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html
      

      crone 表达式:

      【讨论】:

      • 从实例开始 3 小时(或 4 小时等)后,cloudwatch 将如何触发 lambda 函数?
      • 您的 cloudwatch 事件不知道实例启动的时间,因此假设您每半小时或其他更合适的时间间隔触发它。您的目标 lambda 函数将知道 EC2 实例的开始时间。确定开始时间后,您可以采取您想要运行它或停止实例的操作。
      猜你喜欢
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 2013-01-05
      相关资源
      最近更新 更多