我是Python的新手。但是,我已经设法为Lambda定制了Python脚本,以搜索在运行Terraform和Packer之后留下的Packer Builder工件。我正在努力为脚本找到正确的代码行,这些脚本只会删除名称超过2天的带有“ Packer Builder”的实例。我不能立即删除实例。
它与下面的代码一起使用。但是,它不具有检查2天以上实例的功能,我很困惑。这是我到目前为止的内容:
import boto3
import logging
from collections import defaultdict
# Setup simple logging for more info.
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# This will define the connection.
ec2 = boto3.resource('ec2')
# Get information for all running instances
running_instances = ec2.instances.filter(Filters=[{
'Name': 'instance-state-name',
'Values': ['running']}])
ec2info = defaultdict()
for instance in running_instances:
for tag in instance.tags:
if 'Name'in tag['Key']:
name = tag['Value']
# Add instance info to a dictionary
ec2info[instance.id] = {
'Name': name,
'Type': instance.instance_type,
'State': instance.state['Name'],
'Private IP': instance.private_ip_address,
'Public IP': instance.public_ip_address,
'Launch Time': instance.launch_time
}
attributes = ['Name', 'Type', 'State', 'Private IP', 'Public IP', 'Launch Time']
for instance_id, instance in ec2info.items():
for key in attributes:
print("{0}: {1}".format(key, instance[key]))
print("------")
def lambda_handler(event, context):
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
'Name': 'tag:Name',
'Values': ['Packer Builder' + '*']
}
]
# Filter the instances.
instances = ec2.instances.filter(Filters=filters)
# Locate all running instances.
RunningInstances = [instance.id for instance in instances]
# Make sure there are actually instances to shut down.
if len(RunningInstances) > 0:
# Perform the shutdown.
shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).terminate()
print (shuttingDown)