我遇到客户端错误,无法使用Lambda在环境变量中提供实例ID来停止实例,但是当我对实例ID进行硬编码时工作正常
Lambda函数:
instances = ['i-0d66b89b8c010560d']
import boto3
import os
# Enter the region your instances are in. Include only the region without
specifying Availability Zone; e.g., 'us-east-1'
region = 'us-east-1'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
# instances = ['i-0d66b89b8c010560d']
def lambda_handler(event, context):
print 'stopping your instance'
instances = os.environ['INSTANCES_ID']
print instances
print type(instances)
instances = list(instances)
print type(instances)
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + str(instances)
日志输出:
START RequestId: 5c965493-fd10-11e8-9c0f-09f0c600ad35 Version: $LATEST
stopping your instance
i-0d66b89b8c010560d
<type 'str'>
<type 'tuple'>
An error occurred (InvalidInstanceID.Malformed) when calling the
StopInstances operation: Invalid id: "i": ClientError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 18, in lambda_handler
ec2.stop_instances(InstanceIds=instances)
File "/var/runtime/botocore/client.py", line 314, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/var/runtime/botocore/client.py", line 612, in _make_api_call
raise error_class(parsed_response, operation_name)
ClientError: An error occurred (InvalidInstanceID.Malformed) when calling
the StopInstances operation: Invalid id: "i"
答案 0 :(得分:1)
如您在Log输出中所见,您的'instances'是一个值为i-0d66b89b8c010560d
的str。您可能不知道的是str是可迭代的。使列表“通话”的行为与您期望的有所不同。因此,当您调用此代码时:
instances = list(instances)
您实际上是在这样做:
>>> instances = 'i-0d66b89b8c010560d'
>>> list(instances)
['i', '-', '0', 'd', '6', '6', 'b', '8', '9', 'b', '8', 'c', '0', '1', '0', '5', '6', '0', 'd']
看看会发生什么?您的str会转换为列表,其中str的每个索引都是列表中的索引。
因此解决方案是:
instances = ['i-0d66b89b8c010560d']
import boto3
import os
# Enter the region your instances are in. Include only the region without
specifying Availability Zone; e.g., 'us-east-1'
region = 'us-east-1'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
# instances = ['i-0d66b89b8c010560d']
def lambda_handler(event, context):
print 'stopping your instance'
instances = os.environ['INSTANCES_ID']
print instances
print type(instances)
instances = [instances]
print type(instances)
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + str(instances)