首页 > 解决方案 > 如何从 AWS Lambda ListFunctions API 获取与自己的过滤条件匹配的所需记录数量?

问题描述

我尝试listFunctions从 NodeJS 的 AWS-SDK 获取 AWS Lambda 函数。 https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#listFunctions-property

我想要做的是获得与自己的过滤条件相匹配的所需数量的功能;例如,functionName 包含字符串“dev”。这个API有MaxItems,但是我们不能设置过滤条件。

所以我制定了一个策略来实现这一点。设置MaxItems参数等于剩余记录。当我必须获得 50 条过滤记录时,设置MaxItems为 50。

但我认为这种策略效率低下。很明显,当剩余记录数为 1 或其他小数字时,我必须比我需要的更频繁地重复调用 API。

如何在MaxItems数学上确定参数?

标签: node.jsaws-lambda

解决方案


我会用python给你答案,因为我不知道node.js。

最好的事情是您分两步执行此操作:

  1. 首先,检索所有函数,setting MaxItems以一个大数字。

  2. 手动循环遍历函数名称并根据您的条件获取任意数量的函数。

  3. 一旦达到您想要的数字,停止循环并使用matched functions作为输出。

import boto3

lambda_client = boto3.client('lambda')

# pass the NextMarker only if needed!
func_kwargs = dict(MaxItems=1000)
functions_names_returned = list() # this what you want to return
while True:
    response = lambda_client.list_functions(**func_kwargs)
    functions_info = response['Functions']
    all_functions_names = [x['FunctionName'] for x in functions_info]
    functions_names_returned.extend(all_functions_names)
    marker = response.get('NextMarker')
    if not marker:
        break
    func_kwargs['Marker'] = marker

""" 
now you have retrieved all the functions in a list, 
so you can apply any filtering tecnique to retrieve your wanted
functions. I use a for loop for clarity.
"""
print(f'{functions_names_returned=}')
desired_number_of_functions_to_return = 2
count_returned_functions = 0
all_functions_names_list = list() # this what you want to return
for function_name in functions_names_returned:

    if 'dev' in function_name:
        all_functions_names_list.append(function_name)
        count_returned_functions += 1
    if count_returned_functions == desired_number_of_functions_to_return:
        break
        #exit for loop
print(all_functions_names_list)


推荐阅读