Skip to content

Instantly share code, notes, and snippets.

@PopeFelix
Created July 19, 2022 22:40
Show Gist options
  • Select an option

  • Save PopeFelix/d838c53b982491c65b0efe34564c3a9c to your computer and use it in GitHub Desktop.

Select an option

Save PopeFelix/d838c53b982491c65b0efe34564c3a9c to your computer and use it in GitHub Desktop.
List AWS Lambdas by tag
import Log from "@dazn/lambda-powertools-logger"
import {
LambdaClient,
ListFunctionsCommand,
ListFunctionsCommandOutput,
ListTagsCommand,
} from "@aws-sdk/client-lambda"
const lambda = new LambdaClient({})
/**
* Returns a list of names of functions having the given search tag and search tag value
*/
export const listLambdasByTag = async (searchTag: string, searchTagValue: string): Promise<string[]> => {
let counter = 0
let Marker: string | undefined = undefined
const functionNames: string[] = []
do {
let response: ListFunctionsCommandOutput
try {
response = await lambda.send(new ListFunctionsCommand({ MaxItems: 5 })) // Keep this small to avoid throttling errors from ListTags
} catch (e) {
let error: Error = e instanceof Error ? e : new Error(`${e}`)
Log.error("ListFunctions command failed", error)
throw e
}
if (response.Functions) {
Log.debug(`ListFunctions returned ${response.Functions.length} functions`)
const result = await Promise.allSettled(
response.Functions.map(async ({ FunctionArn, FunctionName }) => {
Log.debug(`List tags for ${FunctionName}`)
const response = await lambda.send(new ListTagsCommand({ Resource: FunctionArn }))
Log.debug("ListTags call successful", { response })
Log.debug(`Function ${FunctionName} has ${Object.keys(response.Tags || {}).length} tags`)
if (response.Tags && response.Tags[searchTag] === searchTagValue) {
Log.info(`Function ${FunctionName} is tagged as a custom rule handler`)
functionNames.push(FunctionName as string)
}
})
)
Log.debug("Result of filtering functions by tag", { result, counter })
const failed = result.filter(
(result) => result.status === "rejected"
) as PromiseRejectedResult[]
if (failed.length) {
Log.error(`${failed.length} calls failed`, { reasons: failed.map(({ reason }) => reason) })
throw new Error(failed[0].reason)
}
}
Marker = response.NextMarker
counter++
} while (Marker)
return functionNames
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment