使用IAM从AWS lambda python连接mongodb

frebpwbc  于 2023-03-01  发布在  Go
关注(0)|答案(1)|浏览(142)

到目前为止,我一直使用pymongo[srv]将AWS lambda连接到MongoDB集群:

mongodb+srv://username:password@cluster.name/database

现在,我尝试设置IAM角色连接,在此存储库中有一个连接字符串,例如:

"mongodb://<access_key>:<secret_key>@mongodb.example.com/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<security_token>"

我已经尝试了这一个,但我得到了以下错误在我的Cloudwatch日志:

[ERROR] ValueError: Port must be an integer between 0 and 65535: 'Fizjqbxairn6K19Fsalbucyz'
Traceback (most recent call last):
  File "/var/lang/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/var/task/lambda_function.py", line 13, in <module>
    client = MongoClient(
  File "/var/task/pymongo/mongo_client.py", line 736, in __init__
    res = uri_parser.parse_uri(
  File "/var/task/pymongo/uri_parser.py", line 568, in parse_uri
    nodes = split_hosts(hosts, default_port=default_port)
  File "/var/task/pymongo/uri_parser.py", line 376, in split_hosts
    nodes.append(parse_host(entity, port))
  File "/var/task/pymongo/uri_parser.py", line 137, in parse_host
    raise ValueError("Port must be an integer between 0 and 65535: %r" % (port,))

所以我猜字符串语法是不正确的。
请告诉我在使用AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY env变量时要使用的正确连接字符串是什么:

client = MongoClient(conn_string)

先谢了
编辑:
我的python字符串是:

client = MongoClient('mongodb://' + os.environ.get("AWS_ACCESS_KEY_ID") + ':' + os.environ.get("AWS_SECRET_ACCESS_KEY") + @clustername/databasename?retryWrites=true&authMechanism=MONGODB-AWS)

而且我正在安装pymongo[aws]作为依赖项,而不是pymongo[srv]
编辑2:
我确认AWS_SECRET_ACCESS_KEY包含/作为字符。

2g32fytz

2g32fytz1#

我认为你应该对userName/password/sessionToken(AWS_*)中的值进行转义,在这里搜索aws。换句话说,你在连接字符串中提供的所有值以及可能包含特殊字符(如:/)的值都应该进行转义。请参阅SO question,了解如何在python中执行此操作

相关问题