mongodb - 如何使用 ansible 设置 mongodb 副本集
问题描述
需要在 3 个实例中设置 mongo dB 副本集,一个可以是主要的,其余两个将是辅助的。任何人都可以建议我如何编写剧本。
已在三台服务器中启动了 mongo shell 并启动了复制名称
'''复制:replSetName:“testingrs”'''
解决方案
Ansible 已经为其提供了插件:community.mongodb.mongodb_replicaset
当我部署我的 MongoDB 分片集群时,该插件仍然是 1.0 版本并且有很多限制。我们在安装时也遇到了一些问题pymongo
,所以我手动开发了这些任务。但是,我认为使用当前版本不再需要自己编写任务。
无论如何,我的剧本看起来像这样:
- name: Check if Replicaset is already initialized
shell:
cmd: "/usr/bin/mongo --norc --quiet localhost:{{ ports.config }}"
executable: /bin/bash
stdin: "rs.status().codeName"
register: result
changed_when: false
check_mode: no
- set_fact:
rs_initiate: |
{% set members = [] %}
{% for host in groups['config'] | sort %}
{% set m = {'_id': loop.index0 } %}
{% set _ = m.update({'host': host + '.' + domain + ':' + ports.config | string }) %}
{% set _ = members.append(m) %}
{% endfor %}
{% set init = {'_id': replica_set.conf} %}
{% set _ = init.update({'members': members}) %}
{{ init }}
rs: |
{% set i = (result.stdout == 'NotYetInitialized') %}
{% for host in ansible_play_hosts %}
{% set i = i and (hostvars[host].result.stdout == 'NotYetInitialized') %}
{% endfor %}
{{ {'NotYetInitialized': i} }}
- name: Init Replicaset
shell:
cmd: "/usr/bin/mongo --norc --quiet localhost:{{ ports.config }}"
executable: /bin/bash
stdin: |
rs.initiate({{ rs_initiate | to_json }})
rs.status()
while (! db.isMaster().ismaster ) sleep(1000)
when: rs.NotYetInitialized and inventory_hostname_short == (groups['config'] | sort | first)
我遇到的一个问题是处理身份验证,因为当您从头开始部署 MongoDB 时,不存在任何用户。因此,当您喜欢多次运行剧本时,您必须区分是否使用身份验证。
我的剧本包含以下任务:
- name: Check if authentication is enabled
shell:
cmd: "/usr/bin/mongo --norc --quiet localhost:{{ ports.router }}"
executable: /bin/bash
stdin: "rs.status().codeName"
register: result
ignore_errors: yes
changed_when: false
when: inventory_hostname_short == (groups['application'] | sort | first)
- name: Authenticate if needed
set_fact:
authenticate: "{{ (result.stdout == 'Unauthorized') | ternary('-u admin -p ' + password[env].admin + ' --authenticationDatabase admin','') }}"
when: inventory_hostname_short == (groups['application'] | sort | first)
- name: Create users
shell:
cmd: "/usr/bin/mongo {{ authenticate }} --norc --quiet localhost:{{ ports.router }}"
executable: /bin/bash
stdin: |
admin = db.getSiblingDB("admin")
admin.createUser({ user: "admin", pwd: "{{ password[env].admin }}", roles: ["root"] })
admin.auth("admin", "{{ password[env].admin }}")
// create more users if needed
admin.createUser(...)
when: inventory_hostname_short == (groups['application'] | sort | first)
推荐阅读
- android - 如何判断 jetpack-compose 分页是否有效?
- node.js - 如何使用 npm Jose 创建签名的 JWT,然后验证此令牌?
- python - SQL 触发器是否比接口上的 if 语句快
- r - 在 R ggplot2 中,如何自动绘制垂直线
- r - 如何通过 R 用 excel 中的值填充我的 SQL 表
- django - 来自无“GMAIL_PASSWORD”的 Django/Selenium KeyError
- unity3d - Unity:跟随玩家的主摄像机想要正面朝上
- mongodb - 获取 5 天以来的所有日志
- postgresql - 如何在 postgresql 中对数据进行 minmax 规范化并构建为 json
- python - 如何覆盖模块名称(__name__)?