Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

AWS Lambda to filter EC2 Instances into groups

I needed a way to automatically filter all running EC2 instances by subnet.
What this basically does is getting all running AWS instances and getting the subnet they started in.
Then if it's the first time an instance was found in this subnet it creates a list of that subnet and puts the instance ID in it.
You should get a json of all the subnets you had instances running in and list of all instances that are running inside every subnet list.

You can easily modify it to filter any other tag or sort them differently.
Feel free to ask more if you didn't understand.
(Note that the Lambda you create has to have IAM role with enough permissions for this)

Code
import boto3
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
   filters = [{
        'Name': 'instance-state-name',
        'Values': ['running']
      }]

   instances = ec2.instances.filter(Filters=filters)

   RunningInstances = [instance.id for instance in instances]
   list = {}
   for x in RunningInstances:
    ec2instance = ec2.Instance(x)
    if not list.__contains__(ec2instance.subnet.id):
     list[ec2instance.subnet.id] = []
    list[ec2instance.subnet.id].append(x)
   return(list)


Edit:
Tested it on 120~ machines and it took 30 seconds. Make sure it's set to run for 5 minutes or something.
[Image: C8xRvdD.png]


Possibly Related Threads...
Thread / Author Replies Views Last Post
by daft_dutchSep 11, 2025 08:35 AM 1 124 Sep 11, 2025 08:35 AM
Last Post: Rsynced
[C#] by SirNoslywDec 10, 2017 06:29 PM 8 367 Dec 10, 2017 06:29 PM
Last Post: byte[]
[Python] by datguy.devJun 21, 2017 09:38 PM 0 128 Jun 21, 2017 09:38 PM
Last Post: datguy.dev