Lambda函数用于在SSH服务关闭时启动和停止实例

时间:2017-11-06 06:59:24

标签: lambda

当我们无法SSH服务器时,需要一个lambda函数来启动和停止服务器。 请帮帮我。

1 个答案:

答案 0 :(得分:0)

import boto3
import json
import time
def lambda_handler(event, context):
    print(json.dumps(event, indent=2))
    ec2=boto3.resource('ec2', region_name='us-west-2')
    instances =ec2.instances.filter(Filters=[{'Name': 'tag:Env', 'Values': ['Prod']}])
    for ins in instances:
        print(ins.id)
        if ins.state['Name']!='stopped':
            ins.stop()
            print("Stopping the instance ")
            print(ins.id)
            while ins.state['Name']!='stopped':
                ins.reload()
                time.sleep(5)
                if ins.state['Name']=='stopped':
                    print("Instance "+ins.id+" is stopped now")
                    break

        if ins.state['Name']!='running':
            ins.start()
            print("Starting the instance "+ins.id)
            while ins.state['Name']!='running':
                ins.reload()
                time.sleep(5)
                if ins.state['Name']=='running':
                    print("Instance "+ins.id+" is running now")
                    break