AWS - автоматическое исправление EC2 с публичным IP - PullRequest
0 голосов
/ 04 июня 2019

Глядя на разработку сценария Python, который будет сканировать экземпляры EC2 на наличие публичных IP-адресов и, если найдены, остановить эти экземпляры.

Я новичок в Python, поэтому у меня проблемы с попыткой соединить два куска кода.


ec2Resource = boto3.resource('ec2')
def lambda_handler(event, context):
        instances = ec2Resource.instances.all()
        for instance in instances:
            #print("inst.public_ip_address",inst.public_ip_address)
            if instance.public_ip_address:
                print("Instance ID: ",instance.id," , Instance Platform: ",instance.platform," , Public IP: ",instance.public_ip_address,", Instance Type:",instance.instance_type,",Instance Image Id: ",instance.image.id) 
response = client.stop_instances(
    InstanceIds=[
        'string',
    ],
    Hibernate=True,
    DryRun=False,
    Force=False
)

По сути, ищем автоматический скрипт, который обнаруживает общедоступные IP-адреса на EC2 и затем останавливает их.Приношу свои извинения, если приведенный выше скрипт выглядит как hamburglar

ОБНОВЛЕНИЕ: думаю, я очистил его, чтобы создать списки, а затем из этого списка выполнить остановку.

#!/usr/bin/python
'''
    Finds instance id, Instance Platform, Public IP, instance type based on tags.
    Returns a list of instances found
'''

import boto3

def instances_find(name, value):
    '''
    Finds instance id's based on tags.
    Returns a list of instances found.
    '''
    list_instances = []
    # filter based on tags
    filters =[
        {
        'Name': name,
        'Values': [
            value,
            ]
        },
    ]
    instances = ec2_resource.instances.filter(Filters=filters)
    for instance in instances:
        # for each instance, append to list
        list_instances.append("Instance ID: ",instance.id," , Instance Platform: ",instance.platform," , Public IP: ",instance.public_ip_address,", Instance Type:",instance.instance_type,",Instance Image Id: ",instance.image.id)
    return list_instances

def instances_stop(list):
    '''
    Stops instances defined in the list.
    '''
    ec2_client.stop_instances(InstanceIds=list)

# enter tag name and value
tag_name = 'tag:environment'
tag_value = 'dev'

ec2_resource = boto3.resource('ec2')
ec2_client = boto3.client('ec2')

# find instances
ec2_list = instances_find(tag_name, tag_value)
# stop instances
ec2_stop = instances_stop(ec2_list)
print('stopped instances: ' + str(ec2_list))

...