【发布时间】:2019-08-14 11:49:04
【问题描述】:
我有一个 AWS Lambda 函数可以调整 EC2 实例的大小,但实例 ID 是硬编码的 - 我更喜欢使用标签,但无法让它工作
这是有效的代码:
# lambda function
import boto3
import botocore
import os
# define environment variables
Instance_Type = os.environ['InstanceType']
#define the connections
client = boto3.client('ec2')
RunningInstances = 'i-02a1130833c928708'
def lambda_handler(event, context):
# Stop the instance
client.stop_instances(InstanceIds=[RunningInstances])
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[RunningInstances])
print "Stopped", RunningInstances
# Change the instance type
client.modify_instance_attribute(InstanceId=RunningInstances,
Attribute='instanceType', Value=Instance_Type)
print RunningInstances, "resized down to", Instance_Type
# Start the instance
client.start_instances(InstanceIds=[RunningInstances])
print "Started", RunningInstances
这是我想做的工作:
import boto3
import botocore
import os
# define environment variables
Instance_Type = os.environ['InstanceType']
#define the connections
client = boto3.client('ec2')
#RunningInstances = 'i-02a1130833c928708'
def lambda_handler(event, context):
filters=[
{'Name': 'tag-key', 'Values': ['ResizeDown']},
{'Name': 'tag-value', 'Values': ['True']},
{'Name': 'instance-state-name','Values': ['running']}
]
#filter the instances
instances = client.instances.filter(Filters=filters)
#locate all running instances
RunningInstances = [instance.id for instance in instances]
# Stop the instance
client.stop_instances(InstanceIds=[RunningInstances])
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[RunningInstances])
print "Stopped", RunningInstances
# Change the instance type
client.modify_instance_attribute(InstanceId=RunningInstances,
Attribute='instanceType', Value=Instance_Type)
print RunningInstances, "resized down to", Instance_Type
# Start the instance
client.start_instances(InstanceIds=[RunningInstances])
print "Started", RunningInstances
我得到的错误是:
'EC2' 对象没有属性'instances':AttributeError 回溯(最近一次通话最后): 文件“/var/task/lambda_function.py”,第 21 行,在 lambda_handler 实例 = client.instances.filter(Filters=filters) getattr 中的文件“/var/runtime/botocore/client.py”,第 555 行 self.class.name, item) AttributeError: 'EC2' 对象没有属性 'instances'
【问题讨论】:
标签: python-2.7 amazon-web-services aws-lambda