我使用简单的AWS Lambda函数在给定区域和实例ID的情况下停止EC2实例(请参阅下面的python代码) . Lambda功能由AWS CloudWatch规则触发(特别是每天下午6点的时间表) . 这一切都经过测试和运作 .
import boto3
def lambda_handler(event, context):
region = event.get('region')
instances = event.get('instances')
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'started your instance: ' + str(instances)
如果用户主动登录EC2实例并且触发了该功能,则EC2实例将强制关闭该实例 .
那么,有没有一种方法(在CloudWatch或Lambda中)延迟和/或忽略关闭,直到用户处于非活动状态或完全注销?也许使用boto3代码?
UPDATE:
考虑使用服务员,但我能找到的唯一一个等待直到实例正在使用,而不是使用 . 也许等待呢?还考虑了CloudWatch警报,它可用于在一段时间不活动后停止实例,但不能在确切时间触发 .
waiter = ec2.get_waiter('volume_in_use')
waiter.wait(
WaiterConfig={
'Delay': 900, # In Seconds (900 = 15 mins)
'MaxAttempts': 47 # Number of Attempts (47 = 11.75 hours)
}
) # Default wait is 15 seconds 40 times