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

使用Ansible mongodb_replicaset模块初始化副本集时遇授权错误

解决Ansible community.mongodb.mongodb_replicaset初始化副本集未授权问题

问题背景

使用Ansible的community.mongodb.mongodb_replicaset模块初始化MongoDB 3.6.23副本集时,返回未授权错误,但手动通过mongo shell执行相同命令可成功。环境配置:PyMongo 4.3.3、Python3.8、Ansible 2.9.23,admin用户已赋予最高权限,仅关闭安全验证时模块可正常执行。

核心原因与解决方案

1. PyMongo与MongoDB版本不兼容

MongoDB 3.6.x已终止官方支持,PyMongo 4.x系列不再兼容该版本,导致认证流程异常。

解决步骤:
降级PyMongo至支持MongoDB 3.6的最后一个系列版本:

pip install pymongo==3.12.3

2. 显式指定认证机制与完整连接参数

MongoDB 3.6默认采用SCRAM-SHA-1认证机制,而PyMongo 4.x默认尝试使用更高版本的SCRAM-SHA-256(MongoDB 3.6不支持),同时模块默认可能未显式指定端口,需与手动执行的参数完全对齐。

修改后的Ansible任务:

- name: Initialize MongoDB replica set
  community.mongodb.mongodb_replicaset:
    login_user: admin
    login_password: "{{ admin_password }}"
    login_database: admin
    auth_mechanism: SCRAM-SHA-1
    replica_set: s0
    members:
      - _id: 0
        host: stage-mongoprimary0.server.loc:27017
        priority: 2
      - _id: 1
        host: stage-mongosecondary1.server.loc:27017
        priority: 1
      - _id: 2
        host: stage-mongosecondary2.server.loc:27017
        priority: 1
  when: inventory_hostname == mongo_primary

3. 匹配Ansible与模块版本兼容性

Ansible 2.9.23为旧版本,与最新版community.mongodb模块可能存在适配问题,建议安装兼容的模块版本:

ansible-galaxy collection install community.mongodb:==3.1.0

验证方法

先通过Python脚本测试连接与命令执行,确认环境修复正常:

from pymongo import MongoClient

# 替换{{admin_password}}为实际密码
client = MongoClient('mongodb://admin:{{admin_password}}@stage-mongoprimary0.server.loc:27017/admin?authMechanism=SCRAM-SHA-1')
try:
    # 执行副本集初始化命令
    result = client.admin.command(
        'replSetInitiate',
        {
            '_id': 's0',
            'version': 1,
            'members': [
                {'_id': 0, 'host': 'stage-mongoprimary0.server.loc:27017', 'priority': 2},
                {'_id': 1, 'host': 'stage-mongosecondary1.server.loc:27017', 'priority': 1},
                {'_id': 2, 'host': 'stage-mongosecondary2.server.loc:27017', 'priority': 1}
            ]
        }
    )
    print("副本集初始化成功:", result)
except Exception as e:
    print("错误:", e)

内容的提问来源于stack exchange,提问作者General Zod

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:34:55