지원 중단된 런타임을 사용하는 Lambda 함수에 대한 데이터 가져오기 - AWS Lambda

지원 중단된 런타임을 사용하는 Lambda 함수에 대한 데이터 가져오기

Lambda 런타임이 지원 중단에 가까워지면 Lambda는 이메일을 통해 알림을 보내고 AWS Health Dashboard 및 Trusted Advisor에서 알림을 제공합니다. 이러한 이메일과 알림에는 런타임을 사용하는 함수의 $LATEST 버전이 나열됩니다. AWS Command Line Interface(AWS CLI) 또는 AWS SDK 중 하나를 사용하여 특정 런타임을 사용하는 모든 함수 버전을 나열합니다.

지원 중단될 예정인 런타임을 사용하는 함수가 많은 경우 AWS CLI 또는 AWS SDK를 사용하여 가장 자주 호출되는 함수의 업데이트 우선 순위를 지정할 수도 있습니다.

AWS CLI 및 AWS SDK를 사용하여 특정 런타임을 사용하는 함수에 대한 데이터를 수집하는 방법을 알아보려면 다음 섹션을 참조하십시오.

특정 런타임을 사용하는 함수 버전 목록

AWS CLI(을)를 사용하여 특정 런타임을 사용하는 모든 함수 버전을 나열하려면 다음 명령을 실행합니다. RUNTIME_IDENTIFIER를 지원 중단되는 런타임 이름으로 바꾸고 AWS 리전을 선택합니다. $LATEST 함수 버전만 나열하려면 명령에서 --function-version ALL을 생략합니다.

aws lambda list-functions --function-version ALL --region us-east-1 --output text --query "Functions[?Runtime=='RUNTIME_IDENTIFIER'].FunctionArn"
작은 정보

명령 예제에서는 us-east-1 리전에서 특정 AWS 계정에 대한 함수를 나열합니다. 각 AWS 계정 및 계정이 함수를 보유한 각 기전에서 이 명령을 반복해야 합니다.

AWS SDK 중 하나를 사용하여 특정 런타임을 사용하는 함수를 나열할 수도 있습니다. 다음 예제 코드는 V3 AWS SDK for JavaScript 및 AWS SDK for Python (Boto3)(을)를 사용하여 특정 런타임을 사용하는 함수의 함수 ARN 목록을 반환합니다. 예제 코드는 나열된 각 함수에 대한 CloudWatch 로그 그룹도 반환합니다. 이 로그 그룹을 사용하여 함수의 마지막 간접 호출 날짜를 찾을 수 있습니다. 자세한 내용은 다음 가장 자주 호출된 함수와 가장 최근에 호출된 함수 식별하기 단원을 참조하십시오.

Node.js
예 특정 런타임을 사용하여 함수를 나열하는 JavaScript 코드
import { LambdaClient, ListFunctionsCommand } from "@aws-sdk/client-lambda"; const lambdaClient = new LambdaClient(); const command = new ListFunctionsCommand({ FunctionVersion: "ALL", MaxItems: 50 }); const response = await lambdaClient.send(command); for (const f of response.Functions){ if (f.Runtime == '<your_runtime>'){ // Use the runtime id, e.g. 'nodejs18.x' or 'python3.9' console.log(f.FunctionArn); // get the CloudWatch log group of the function to // use later for finding the last invocation date console.log(f.LoggingConfig.LogGroup); } } // If your account has more functions than the specified // MaxItems, use the returned pagination token in the // next request with the 'Marker' parameter if ('NextMarker' in response){ let paginationToken = response.NextMarker; }
Python
예 특정 런타임을 사용하여 함수를 나열하는 Python 코드
import boto3 from botocore.exceptions import ClientError def list_lambda_functions(target_runtime): lambda_client = boto3.client('lambda') response = lambda_client.list_functions( FunctionVersion='ALL', MaxItems=50 ) if not response['Functions']: print("No Lambda functions found") else: for function in response['Functions']: if function['PackageType']=='Zip' and function['Runtime'] == target_runtime: print(function['FunctionArn']) # Print the CloudWatch log group of the function # to use later for finding last invocation date print(function['LoggingConfig']['LogGroup']) if 'NextMarker' in response: pagination_token = response['NextMarker'] if __name__ == "__main__": # Replace python3.12 with the appropriate runtime ID for your Lambda functions list_lambda_functions('python3.12')

AWS를 사용하여 ListFunctions 작업으로 함수를 나열하는 방법에 대해 자세히 알아보려면 원하는 프로그래밍 언어에 대한 SDK 설명서를 참조하세요.

AWS Config 고급 쿼리 기능을 사용하여 영향을 받는 런타임을 사용하는 모든 함수를 나열할 수도 있습니다. 이 쿼리는 함수의 $LATEST 버전만 반환하지만, 단일 명령으로 모든 리전과 여러 AWS 계정에서 함수를 나열하도록 쿼리를 집계할 수 있습니다. 자세한 내용은 AWS Config 개발자 안내서에서 Querying the Current Configuration State of AWS Auto Scaling Resources를 참조하세요.

가장 자주 호출된 함수와 가장 최근에 호출된 함수 식별하기

지원이 중단될 예정인 런타임을 사용하는 함수가 AWS 계정에 포함된 경우 자주 호출되는 함수나 최근에 호출된 함수를 우선적으로 업데이트하는 것이 좋습니다.

함수가 적은 경우 CloudWatch Logs 콘솔을 사용하여 함수의 로그 스트림을 살펴봄으로써 이 정보를 수집할 수 있습니다. 자세한 내용은 CloudWatch Logs로 전송된 로그 데이터 보기를 참조하세요.

Lambda 콘솔에 표시된 CloudWatch 지표 정보를 사용하여 최근 함수 호출 수를 확인하기 이 정보를 보려면 다음을 수행합니다.

  1. Lambda 콘솔의 함수 페이지를 엽니다.

  2. 호출 통계를 보는 함수를 선택합니다.

  3. 모니터링 탭을 선택합니다.

  4. 날짜 범위 선택기를 사용하여 통계를 보려는 기간을 설정합니다. 최근 호출은 호출 창에 표시됩니다.

함수 수가 많은 계정의 경우 DescribeLogStreamsGetMetricStatistics API 작업을 사용하여 AWS CLI 또는 AWS SDK 중 하나를 사용하여 프로그래밍 방식으로 이 데이터를 수집하는 것이 더 효율적일 수 있습니다.

다음 예제에서는 V3 AWS SDK for JavaScript 및 AWS SDK for Python (Boto3)(을)를 사용하여 특정 함수의 마지막 호출 날짜를 식별하고 최근 14일 동안 특정 함수에 대한 호출 수를 확인하는 코드 스니펫을 제공합니다.

Node.js
예 함수의 마지막 호출 시간을 찾는 JavaScript 코드
import { CloudWatchLogsClient, DescribeLogStreamsCommand } from "@aws-sdk/client-cloudwatch-logs"; const cloudWatchLogsClient = new CloudWatchLogsClient(); const command = new DescribeLogStreamsCommand({ logGroupName: '<your_log_group_name>', orderBy: 'LastEventTime', descending: true, limit: 1 }); try { const response = await cloudWatchLogsClient.send(command); const lastEventTimestamp = response.logStreams.length > 0 ? response.logStreams[0].lastEventTimestamp : null; // Convert the UNIX timestamp to a human-readable format for display const date = new Date(lastEventTimestamp).toLocaleDateString(); const time = new Date(lastEventTimestamp).toLocaleTimeString(); console.log(`${date} ${time}`); } catch (e){ console.error('Log group not found.') }
Python
예 함수의 마지막 호출 시간을 찾는 Python 코드
import boto3 from datetime import datetime cloudwatch_logs_client = boto3.client('logs') response = cloudwatch_logs_client.describe_log_streams( logGroupName='<your_log_group_name>', orderBy='LastEventTime', descending=True, limit=1 ) try: if len(response['logStreams']) > 0: last_event_timestamp = response['logStreams'][0]['lastEventTimestamp'] print(datetime.fromtimestamp(last_event_timestamp/1000)) # Convert timestamp from ms to seconds else: last_event_timestamp = None except: print('Log group not found')
작은 정보

ListFunctions API 작업을 사용하여 함수의 로그 그룹 이름을 찾을 수 있습니다. 이 작업을 수행하는 방법의 예는 특정 런타임을 사용하는 함수 버전 목록을(를) 참조하세요.

Node.js
예 최근 14일간의 호출 횟수를 찾기 위한 JavaScript 코드
import { CloudWatchClient, GetMetricStatisticsCommand } from "@aws-sdk/client-cloudwatch"; const cloudWatchClient = new CloudWatchClient(); const command = new GetMetricStatisticsCommand({ Namespace: 'AWS/Lambda', MetricName: 'Invocations', StartTime: new Date(Date.now()-86400*1000*14), // 14 days ago EndTime: new Date(Date.now()), Period: 86400 * 14, // 14 days. Statistics: ['Sum'], Dimensions: [{ Name: 'FunctionName', Value: '<your_function_name>' }] }); const response = await cloudWatchClient.send(command); const invokesInLast14Days = response.Datapoints.length > 0 ? response.Datapoints[0].Sum : 0; console.log('Number of invocations: ' + invokesInLast14Days);
Python
예 최근 14일간의 호출 횟수를 찾기 위한 Python 코드
import boto3 from datetime import datetime, timedelta cloudwatch_client = boto3.client('cloudwatch') response = cloudwatch_client.get_metric_statistics( Namespace='AWS/Lambda', MetricName='Invocations', Dimensions=[ { 'Name': 'FunctionName', 'Value': '<your_function_name>' }, ], StartTime=datetime.now() - timedelta(days=14), EndTime=datetime.now(), Period=86400 * 14, # 14 days Statistics=[ 'Sum' ] ) if len(response['Datapoints']) > 0: invokes_in_last_14_days = int(response['Datapoints'][0]['Sum']) else: invokes_in_last_14_days = 0 print(f'Number of invocations: {invokes_in_last_14_days}')