Лямбда, python boto3, удалить экземпляр старше x дней - PullRequest
0 голосов
/ 26 сентября 2018

Я очень плохо знаком с Python.Однако мне удалось настроить скрипт Python для Lambda для поиска артефактов Packer Builder, оставшихся после запуска Terraform и Packer.Я изо всех сил пытаюсь найти правильную строку кода для моего сценария, который будет удалять только экземпляры с «Packer Builder» с именем старше 2 дней.Я не могу, чтобы он сразу удалял экземпляры.

Работает с кодом ниже.Однако он не имеет функции проверки экземпляров старше 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)
...