AWS中是否有任何服务可以在特定时间启动和停止实例?

时间:2019-08-26 10:33:41

标签: amazon-web-services amazon-ec2

我有一个EC2实例,我想在晚上12:00停止并每天晚上7点重新启动一次。是否有任何AWS服务可以实现这一目标?

任何帮助将不胜感激

4 个答案:

答案 0 :(得分:4)

有足够的示例,您可以按照aws的官方链接进行操作。

如果您正在寻找简单的解决方案,建议您使用AWS lambda和cloudwatch https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/

如果您正在寻找可靠的解决方案,请按照之前的文档中所述,https://aws.amazon.com/premiumsupport/knowledge-center/stop-start-instance-scheduler/

答案 1 :(得分:1)

有几种不同的方法可以做到这一点。

  1. 使用定时缩放事件创建ASG。在12:00 AM扩展为0个实例,在7:00 PM扩展为1个实例。超级简单!
  2. 使用CloudCustodian并创建托管策略。
  3. 在这里使用参考拱门:https://aws.amazon.com/solutions/instance-scheduler/

答案 2 :(得分:1)

您可以使用两种方法,两种lambda函数来执行此操作,或者使用一种方法来执行此操作,但是为此,您可能需要检查触发时间,第二种是使用带有cron作业的AWS CLI使用bash脚本。

使用Lambda:

  1. Lambda函数可在12:00 AM停止实例
  2. Lambda函数可在晚上7点启动实例

重要这两个Lambda都应基于预定事件。请记住,时间是在 UTC 中。

enter image description here

1。要停止

region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)
    print 'stopped your instances: ' + str(instances)
  1. 开始
import boto3
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.start_instances(InstanceIds=instances)
    print 'started your instances: ' + str(instances)

拉姆达角色

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:Start*",
        "ec2:Stop*"
      ],
      "Resource": "*"
    }
  ]
}

您可以阅读有关herehere这种方法的更多详细信息。

使用AWS cli和Cron Job

stop.sh

#!/bin/bash
ID="i-1234567890abcdef0"
echo "stop instance having ID=$ID
aws ec2 stop-instances --instance-ids $ID

start.sh

#!/bin/bash
echo "starting instance....."
aws ec2 start-instances --instance-ids i-1234567890abcdef0

日常工作

停止

0 0 * * * stop.sh 开始

0 7 * * * start.sh

使用第二种方法,您将节省Lamda函数的资源和成本。

答案 3 :(得分:1)