当我们无法SSH服务器时,需要一个lambda函数来启动和停止服务器。 请帮帮我。
答案 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