在AWS Lambda函数中使用AWS SDK for Python (boto3)设置Kafka事件源ARN和lambda执行角色ARN,如下所示:
import boto3
def lambda_handler(event, context):
client = boto3.client('lambda')
response = client.get_function_configuration(
FunctionName='lambda-function-name'
)
arn = response['Role']
client = boto3.client('kafka')
response = client.list_clusters()
cluster_arn = response['ClusterInfoList'][0]['ClusterArn']
client = boto3.client('lambda')
response = client.create_event_source_mapping(
EventSourceArn=cluster_arn,
FunctionName='lambda-function-name',
Enabled=True,
BatchSize=1,
StartingPosition='LATEST',
MaximumBatchingWindowInSeconds=60,
BisectBatchOnFunctionError=True,
DestinationConfig={
'OnSuccess': {
'Destination': 'arn:aws:logs:us-east-1:111122223333:destination:MyDestination'
}
},
MaximumRecordAgeInSeconds=604800,
MaximumRetryAttempts=10,
ParallelizationFactor=1
)
在此示例中,lambda-function-name
指的是 AWS Lambda 函数的名称,arn
是 lambda-function-name
执行角色的 ARN,而 cluster_arn
是 Kafka 事件源 ARN。最后,使用 create_event_source_mapping
方法将事件源映射到 Lambda 函数。
要使此解决方法工作,确保角色和事件源都在同一帐户中。