Jun 10, 2020 02:53 PM
(This post was last modified: Jun 11, 2020 08:09 AM by Zero.)
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)
Edit:
Tested it on 120~ machines and it took 30 seconds. Make sure it's set to run for 5 minutes or something.
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]](https://i.imgur.com/C8xRvdD.png)

