def getSubnets()

in resource-selector-lambda/handler.py [0:0]


    def getSubnets(self, config, vpclist):
        # subnets list placeholder
        subnetdict = {}
        # build up boto3 client for EC2
        ec2 = boto3.resource('ec2', region_name=self.region)

        # Loop through VPC(s)
        for vpcid in vpclist:
            # Use the vpcid parameter to create a vpc object
            logger.info(f'VPC id = {vpcid}')
            vpc = ec2.Vpc(vpcid)
            logger.info('f VPC object: {vpc}')
            # Loop through subnets
            for subnet in vpc.subnets.all():
                logger.info(f'subnet: {subnet.id}')
                # I found a subnet, ;let's inspect the tags
                if subnet.tags and self.searchObject(subnet.tags, config):
                    # subnet macth criteria; let's verify available IP
                    # we want to return only subnets with number of availablle IP
                    # specified in configuration
                    if subnet.available_ip_address_count > self.availableIp:
                        subnetdict[subnet.id] = subnet.available_ip_address_count
                        logger.info (f'free ips: {subnet.available_ip_address_count}')
                # if not tags criteria specified in configuration, return all subnets
                elif not subnet.tags and not 'Tags' in config:
                    # Verify available IP
                    if subnet.available_ip_address_count > self.availableIp:
                        subnetdict[subnet.id] = subnet.available_ip_address_count
                        logger.info (f'free ips: {subnet.available_ip_address_count}')

        # look at our dict, should contain subnets with free ips
        logger.info(f'Subnet list = {subnetdict}')
        # turn dict into a string to allow the shuffling.
        subnetlist = list(subnetdict.keys())
        # randomize the list to prevent constant selection of a subnet by position.
        random.shuffle(subnetlist)
        # turn list into a comma separated string and place it in our response
        self.setOutput(subnetlist)