其实我想减少AWS的账单。我在我的项目中使用了一些实例。我想在一定的时间段后(每第3-4小时)在我的登录电子邮件ID上发出通知,并在特定的时间期限内关闭。那么,我怎样才能做到这一点呢?
if current time - instance start time >= 3 hr (send a mail)
if current time - instance start time >= 4 hr (send a mail)
if current time - instance start time >= 5 hr (shut down that instance)
对于你的用例,我已经编码了一个代码 停止器 可以在给定的持续时间后停止终止实例。
此外,它还可以在给定的运行持续时间后向 Amazon SNS 主题发送通知。
请看 GutHub: 简单的Lambda Stopinator。类型2
它是通过标签来控制的。
标签名称 (按优先顺序):
Terminate-After
: 终止实例Stop-After
: 停止实例Notify-After
: 如果仍在运行,则发送SNS通知(多个通知时,使用 Notify-After1
, Notify-After2
等)。)标签值。 表示运行时间(如'30m'、'1.5h'、24h')。
使用以下方法安排Lambda函数定期运行(例如每5分钟)。亚马逊云观察活动.
更多详情,请看。Lambda中的简单EC2 Stopinator - DEV社区
您可以通过设置云观察事件并使用 cron 表达式来安排。Goto: AWS控制台 -> cloudwatch -> Events -> Rules -> create rule -> schedule -> enter your desired crone expression -> target (你的lambda函数将执行任务).
ec2_client = boto3.client('ec2')
response = ec2_client.describe_instance_status()
#response can give detail about other and particular instance also
instance_status_details = response['InstanceStatuses'][0]['InstanceStatus']['Details']
#there is impairedSince parameter (inside instance_status_detail) to figure out when you launched this instance
#take from this link https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html