我在使用 boto3 从Chalice部署的 Lambda 启动 EC2 实例时遇到问题。
相关代码是这样的:
resource = boto3.resource('ec2')
instance = resource.Instance(params['instance_id'])
if params['action'] == 'run':
try:
response = instance.start()
except BaseException as be:
logging.exception("Error: Failed to start instance" + str(be) )
raise ChaliceViewError("Internal error at server side")
else:
try:
response = instance.stop(Force=True)
except BaseException as be:
logging.exception("Error: Failed to stop instance" + str(be) )
raise ChaliceViewError("Internal error at server side")
请求似乎成功了。例如,在调用“start()”方法的 2 种情况下,boto3 响应是这样的:
{"Status":{"StartingInstances":[{"CurrentState":{"Code":0,"Name":"pending"},"InstanceId":"i-0129bb4079559e5bc","PreviousState":{"Code":80,"Name":"stopped"}}],"ResponseMetadata":{"RequestId":"d88a9fbc-f2f2-4c51-9629-30a63c7e753b","HTTPStatusCode":200,"HTTPHeaders":{"x-amzn-requestid":"d88a9fbc-f2f2-4c51-9629-30a63c7e753b","content-type":"text/xml;charset=UTF-8","content-length":"579","date":"Wed, 23 Sep 2020 16:59:40 GMT","server":"AmazonEC2"},"RetryAttempts":0}}}
另一个回应是这样的:
{"Status":{"StartingInstances":[{"CurrentState":{"Code":0,"Name":"pending"},"InstanceId":"i-0129bb4079559e5bc","PreviousState":{"Code":80,"Name":"stopped"}}],"ResponseMetadata":{"RequestId":"2bde553a-87f1-4fe0-a13a-8b4db4c0dbbc","HTTPStatusCode":200,"HTTPHeaders":{"x-amzn-requestid":"2bde553a-87f1-4fe0-a13a-8b4db4c0dbbc","content-type":"text/xml;charset=UTF-8","content-length":"579","date":"Wed, 23 Sep 2020 17:07:58 GMT","server":"AmazonEC2"},"RetryAttempts":0}}}
但是,在这两种情况下,实例都没有启动,AWS 控制台中的实例状态保持在“已停止”。
当我在 python 控制台中尝试相同的代码片段时,它起作用了,并且实例成功启动:
>>> import boto3
>>> resource = boto3.resource('ec2')
>>> instance = resource.Instance('i-0129bb4079559e5bc')
>>> response = instance.start()
>>> response
{'StartingInstances': [{'CurrentState': {'Code': 0, 'Name': 'pending'}, 'InstanceId': 'i-0129bb4079559e5bc', 'PreviousState': {'Code': 80, 'Name': 'stopped'}}], 'ResponseMetadata': {'RequestId': '535224cc-21d8-45fa-a4a2-0ac984cdfe9a', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '535224cc-21d8-45fa-a4a2-0ac984cdfe9a', 'content-type': 'text/xml;charset=UTF-8', 'content-length': '579', 'date': 'Wed, 23 Sep 2020 17:05:10 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}
有没有人见过这种行为?我有什么明显的遗漏吗?