简体   繁体   English

错误“EC2”对象在 aws lambda 函数中没有属性“实例”

[英]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.

相关问题 在Python中切换AWS账户-EC2对象没有属性'instances'错误 - Switch AWS Accounts in Python - EC2 Object has no attribute 'instances' error 使用 AWS Lambda 函数从 EC2 实例检索信息 - Retrieving info from EC2 instances using AWS Lambda function 用于重新启动 ec2 实例的 aws lambda python 函数不起作用 - aws lambda python function to reboot ec2 instances not working 如何仅允许从VPC内的EC2实例调用AWS Lambda函数 - How to allow invoking an AWS Lambda function only from EC2 instances inside a VPC 使用 AWS Lambda 计算正在运行和停止的 Ec2 实例 - Count Running and Stopped Ec2 Instances with AWS Lambda boto3:AttributeError:'EC2'对象没有属性'create_instances' - boto3 : AttributeError: 'EC2' object has no attribute 'create_instances' Python AWS Lambda Function “”errorMessage“:”“功能” ZA8CFDE6331BD59EB66AC96F8911 - Python AWS Lambda Function “”errorMessage“: ”'function' object has no attribute 'loads'" Boto3 EC2.Client DescribeFleets类错误“ EC2”对象没有属性“ describe_fleets” - Boto3 EC2.Client DescribeFleets class error 'EC2' object has no attribute 'describe_fleets' 从 AWS Lambda 在 AWS EC2 中调用 Flask 端点时出错 - Error calling Flask endpoint in AWS EC2 from AWS Lambda AWS Lambda 错误:AttributeError 'list' 对象没有属性 'get' - AWS Lambda ERROR: AttributeError 'list' object has no attribute 'get'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM