作者:大眼睁睁 | 来源:互联网 | 2023-08-21 21:41
概述:
我们要在aws上实现定时任务,例如:操作aws的ec2实例实现定时开关机需求,如何实现?最简便的方法是使用aws的lambda函数服务+EventBridge定时器服务
实现办法:
1.登录aws控制台,搜索lambda服务:

2.点击进去之后创建新函数:


3.编辑函数名称(自定义,使用英文),运行语言,基本常用的python,ruby,nodejs,java,go等全部支持,选择自己擅长的语言即可:

4.权限这块需要注意下,因为登录的账号角色不一定有aws某个服务的权限,例如有lambda的权限,但是你要操作ec2实例,但是没有ec2实例的权限,这个到了test的时候会有日志,到时候具体问题具体分析,我们这里选择创建新角色:

5.创建完之后编写lambda函数的代码-我们以启动ec2实例为例子,代码如下:
import boto3# Enter the region your instances are in, e.g. 'us-east-1'region = 'ap-test' ## ec2实例所在区域# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']instances = ['i-0424dddddd1222'] ## 实例iddef lambda_handler(event, context):ec2 = boto3.client('ec2', region_name=region)ec2.start_instances(InstanceIds=instances)print('启动ec2实例: ' + str(instances))

6.编写完点击deploy保存代码,然后点击配置:

7.在配置里修改点击编辑,修改3个重要的参数,修改完之后点击保存:

重要:(不修改会导致日志报各种奇怪的错)
内存修改为:1024M
短暂存储修改为:512M
超时时间修改为:15分钟
角色选择4里自建或者已有权限的角色

8.返回代码编辑部分,已保存代码,点击Test测试代码是否可以正常运行:
目前此ec2实例处于关机状态,测试是否可以通过lambda函数实现操作它开机

函数显示测试成功,返回ec2服务页面查看实例是否启动:

实例也正常启动了,证明lambda函数已生效:
9.在EventBridge里添加定时任务:

10.创建新规则:

如果是长期定时的周期性任务选择计划类
举例:每天的12:20执行任务
注意:
时间选择本地时间,否则会导致与实际时间不相符
因为aws ec2的时区是utc时间,所以其实实际情况是:你想要当前上午12点20执行任务,你必须设置本地时区时间并且往前推算8小时,也就是12点20的任务,cron里输入 20 04 * * ? *

11.点击下一步保存(最好是找个调试完的就近时间测试下)
12.创建完之后可以看到在EventBridge定时服务里已经生效

13.也可以在cloudwatch里去查看定时任务的执行日志, 去判断定时任务是否每天正常在运行
