[英]Error 'EC2' object has no attribute 'instances' in the aws lambda function
After testing this code, I get this error:测试此代码后,我收到此错误:
'EC2' object has no attribute 'instances': AttributeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 11, in lambda_handler
instances=ec2.instances.filter(Filters=filters)
AttributeError: 'EC2' object has no attribute 'instances'
Line 11 is the last line in the code bellow第 11 行是下面代码中的最后一行
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
filters = [{ 'Name': 'instance-state-name', 'Values': ['running']}]
instances=ec2.instances.filter(Filters=filters)
Where exactly is the error here?这里的错误究竟在哪里?
使用EC2.Client.describe_instances()
方法:
instances=ec2.describe_instances(Filters=filters)
Alternatively to Leon's answer you can use the EC2.ServiceResource
class: EC2.ServiceResource
Leon 的回答,您还可以使用EC2.ServiceResource
类:
ec2 = boto3.resource('ec2', region_name=region)
Because calling ec2.instances.filter()
has the benefit of returning a list of resources list(ec2.Instance)
(instead of a dict
), on which you can call methods like start()
, stop()
, etc. directly:因为调用ec2.instances.filter()
具有返回资源list(ec2.Instance)
(而不是dict
)的好处,您可以直接调用start()
、 stop()
等方法:
filters = [{ 'Name': 'instance-state-name', 'Values': ['running']}]
instances=ec2.instances.filter(Filters=filters)
for instance in instances:
instance.stop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.