You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Lambda中传入global bundle.pem连接DocumentDB?

AWS Lambda连接Amazon DocumentDB证书文件找不到问题解决

问题描述

尝试用AWS Lambda写入Amazon DocumentDB,连接时需验证证书,已通过Lambda Layer传入global-bundle.pem并设置路径为/opt/global-bundle.pem,但代码报错文件不存在,不过在NoSQLBooster中可正常连接。

相关代码:

import json
import pymongo
import os

CERTIFICATE_PATH = "/opt/global-bundle.pem"

MONGO_URI = f"mongodb://XXXX.cluster-chs6wio2st92.ap-XXX-X.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=.{CERTIFICATE_PATH}&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false"
DATABASE_NAME = "XX"
COLLECTION_NAME = "XX"

client = pymongo.MongoClient(MONGO_URI)
db = client[DATABASE_NAME]
collection = db[COLLECTION_NAME]

def lambda_handler(event, context):
    try:
        trial_data = {
        "trial_id": "1",
        "name": "trial 1",
        "description": "lambda db trial",
    }
    
    result = collection.insert_one(trial_data)
    
    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'Data inserted successfully', 'inserted_id': str(result.inserted_id)})
    }
except Exception as e:
    return {
        'statusCode': 500,
        'body': json.dumps({'error': str(e)})
    }

错误信息:

[ERROR] FileNotFoundError: [Errno 2] No such file or directory: '/opt/global-bundle.pem'
Traceback (most recent call last):

解决步骤

  • 修正证书路径拼接错误:你的MONGO_URI中tlsCAFile参数写了.{CERTIFICATE_PATH},会导致路径变成./opt/global-bundle.pem,但Lambda Layer文件实际路径为/opt/global-bundle.pem,无需前置点号。修改后的MONGO_URI:
    MONGO_URI = f"mongodb://XXXX.cluster-chs6wio2st92.ap-XXX-X.docdb.amazonaws.com:27017/?tls=true&tlsCAFile={CERTIFICATE_PATH}&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false"
    
  • 调整客户端初始化位置:将pymongo.MongoClient等数据库初始化代码移到lambda_handler函数内部,避免Lambda冷启动阶段提前加载资源引发的路径异常:
    def lambda_handler(event, context):
        try:
            client = pymongo.MongoClient(MONGO_URI)
            db = client[DATABASE_NAME]
            collection = db[COLLECTION_NAME]
            
            trial_data = {
                "trial_id": "1",
                "name": "trial 1",
                "description": "lambda db trial",
            }
            
            result = collection.insert_one(trial_data)
            
            return {
                'statusCode': 200,
                'body': json.dumps({'message': 'Data inserted successfully', 'inserted_id': str(result.inserted_id)})
            }
    
  • 验证Lambda Layer结构:确保Layer压缩包的根目录直接包含global-bundle.pem,不要嵌套在子文件夹中,这样解压后文件才会直接出现在/opt/目录下。

内容的提问来源于stack exchange,提问作者Nidhish Krishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 02:57:15