使用lambda与cloudwatch实现定时开关EC2

时间:2019-06-24
本文章向大家介绍使用lambda与cloudwatch实现定时开关EC2,主要包括使用lambda与cloudwatch实现定时开关EC2使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

aws的ec2实例是按需收费的,部分用户在使用ec2过程中发现其业务主要是在一天的某段时间,其余的时候 ec2是闲置空转的状态。而闲置的时候又要被aws计时收费。 所以笔者就想能不能通过aws的Lambda服务,来实现定时开关机,从而减少不必要的费用。

 

用户需求: 在晚上10:00~第二天早上10:00这段时间, 将ec2实例自动关机, 早上10:00~晚上10:00 这段时间ec2自动开机运行

 

步骤:

 

  • 创建停止和启动 EC2 实例的 Lambda 函数

1.在aws console 中选择Lambda服务创建函数

2.对于名称,输入函数的名称,例如“StartStop-XXXX”

3.创建新的IAM角色,策略可参考如下代码:

 

{

  "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": "*"

    }

  ]

}

 

4.创建完角色后返回Lambda控制台,编写Start代码,语法参考如下:

 

import boto3

region = 'cn-northwest-1'

instances = ['i-xxxxxxxxxxxxxxxx, 'i-xxxxxxxxxxxxxxxx']

 

def lambda_handler(event, context):

    ec2 = boto3.client('ec2', region_name=region)

    ec2.start_instances(InstanceIds=instances)

print 'started your instances: ' + str(instances)

 

5.保存此代码版本,标注版本V1

6.现在做stop部分的修改:

 

import boto3

region = ' cn-northwest-1'

instances = ['i-xxxxxxxxxxxxxxxx, 'i-xxxxxxxxxxxxxxxx']

 

def lambda_handler(event, context):

    ec2 = boto3.client('ec2', region_name=region)

    ec2.stop_instances(InstanceIds=instances)

    print 'stopped your instances: ' + str(instances)

 

7.保存此版本标注V2

 

二.控制台选择Cloudwatch服务,创建规则

 

1.事件源“”选择“计划”,笔者选择“cron表达式” ,输入 “0 2 * * ? *”

2.Cron的具体格式可参考官方文档

https://docs.aws.amazon.com/zh_cn/AmazonCloudWatch/latest/events/ScheduledEvents.html

此处一定注意!!!cron 使用的时间是UTC时间!环境是我们国内的话,时间要以当前北京时间-8.

具体UTC时间可查询此网站:https://time.is/UTC

3.在“目标”处选择“Lambda函数”,选择函数名,配置版本处点击“版本,”’选择“V1”。

4.点击“配置规则详细信息”,文件名和描述均写“StartEC2”

5.重复步骤2操作,这时cron表达式为“0 14 * * ? *”

6.重复上文3,4两步骤,函数版本选择“V2”。文件名和描述均写“StopEC2”

7.测试,若机器到时间未停止,首先检查cron表达式和UTC时间表述。其次检查Lambda代码中的instance ID,region是否正确。