Hack Forums
[Python] AWS Lambda to filter EC2 Instances into groups - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] AWS Lambda to filter EC2 Instances into groups (/showthread.php?tid=6086428)



AWS Lambda to filter EC2 Instances into groups - Zero - Jun 10, 2020

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.