如何从 AWS Lambda ListFunctions API 获取与自己的筛选条件匹配的所需数量的记录?



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

我想做的是获得所需数量的函数,这些函数与自己的过滤条件匹配;例如,函数名称包含字符串"dev"。 这个接口有MaxItems,但我们不能设置过滤条件。

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

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

如何以数学方式确定MaxItems参数?

我会用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)

最新更新