存档说明:这篇 2019 年的文章包含历史指导,包括不再支持的 Python 版本。
当时,这个博客运行在一台 EC2 实例上。为节约成本,我没有配置负载均衡器,而是使用期望容量为 1 的 Auto Scaling 组。数据库连接偶尔会出问题,最简单的自动恢复办法是重启实例。不过,没有负载均衡器,这件事并不那么直接,于是我把操作过程记了下来。
- 创建 Route 53 健康检查。
- 找到对应的 CloudWatch 告警,关联一个 SNS 主题。
- 让 SNS 主题向自己发送邮件,并调用 Lambda 函数。
- 确认 Lambda 的 IAM 角色具有重启相应 EC2 实例的权限。
下面这段 Lambda 代码来自网上。写作当时使用的是 Python 2.7,而不是 Python 3.x。
import boto3
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)


云 / 系统