├── molecule ├── cluster │ ├── host_vars │ │ ├── test-multi-01.yml │ │ ├── test-multi-03.yml │ │ └── test-multi-02.yml │ ├── verify.yml │ ├── templates │ │ └── hosts.j2 │ ├── converge.yml │ ├── group_vars │ │ └── all.yml │ └── molecule.yml └── default │ ├── converge.yml │ ├── verify.yml │ ├── host_vars │ └── test-multi-01.yml │ └── molecule.yml ├── .ansible-lint ├── templates ├── tuned.j2 ├── disable-transparent-hugepages.service.j2 ├── mongod_init.conf.j2 └── mongod.conf.j2 ├── meta └── main.yml ├── tasks ├── main.yml ├── numa.yml ├── user_init.yml ├── user.yml ├── reset.yml ├── thp.yml ├── config.yml ├── backup.yml ├── assert.yml ├── keyfile.yml ├── install.yml ├── cluster.yml └── scale.yml ├── .gitlab-ci.yml ├── defaults └── main.yml ├── playbooks └── update.yml ├── LICENSE └── README.md /molecule/cluster/host_vars/test-multi-01.yml: -------------------------------------------------------------------------------- 1 | --- 2 | mongo_replication_role: arbiter 3 | -------------------------------------------------------------------------------- /molecule/cluster/host_vars/test-multi-03.yml: -------------------------------------------------------------------------------- 1 | --- 2 | mongo_replication_role: primary 3 | -------------------------------------------------------------------------------- /molecule/cluster/host_vars/test-multi-02.yml: -------------------------------------------------------------------------------- 1 | --- 2 | mongo_replication_role: secondary 3 | -------------------------------------------------------------------------------- /.ansible-lint: -------------------------------------------------------------------------------- 1 | --- 2 | skip_list: 3 | - command-instead-of-shell 4 | - no-handler 5 | - yaml 6 | - package-latest 7 | -------------------------------------------------------------------------------- /molecule/default/converge.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Converge 3 | hosts: test-multi-01 4 | roles: 5 | - ../ansible_role_mongodb 6 | -------------------------------------------------------------------------------- /molecule/cluster/verify.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Verify 3 | hosts: all 4 | tasks: 5 | - name: several tests should come here 6 | assert: 7 | that: true 8 | -------------------------------------------------------------------------------- /molecule/default/verify.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Verify 3 | hosts: all 4 | tasks: 5 | - name: several tests should come here 6 | assert: 7 | that: true 8 | -------------------------------------------------------------------------------- /templates/tuned.j2: -------------------------------------------------------------------------------- 1 | {{ ansible_managed | comment }} 2 | 3 | [main] 4 | include=virtual-guest 5 | 6 | [vm] 7 | transparent_hugepages=never 8 | 9 | [disk] 10 | readahead=32 11 | -------------------------------------------------------------------------------- /templates/disable-transparent-hugepages.service.j2: -------------------------------------------------------------------------------- 1 | {{ ansible_managed | comment }} 2 | 3 | [Unit] 4 | Description=Disable Transparent Huge Pages (THP) 5 | DefaultDependencies=no 6 | After=sysinit.target local-fs.target 7 | Before=mongod.service 8 | [Service] 9 | Type=oneshot 10 | ExecStart=/bin/sh -c 'echo never | tee /sys/kernel/mm/transparent_hugepage/enabled > /dev/null' 11 | [Install] 12 | WantedBy=basic.target 13 | -------------------------------------------------------------------------------- /meta/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | galaxy_info: 3 | author: Kevin Csuka 4 | description: Ansible role to setup and configure MongoDB 5 | namespace: kcsuka 6 | role_name: mongodb 7 | license: Apache License, Version 2.0 8 | min_ansible_version: 2.9 9 | platforms: 10 | - name: EL 11 | versions: 12 | - 8 13 | galaxy_tags: 14 | - database 15 | - mongodb 16 | - mongo 17 | - cluster 18 | - arbiter 19 | - system 20 | - nosql 21 | 22 | dependencies: [] 23 | -------------------------------------------------------------------------------- /molecule/cluster/templates/hosts.j2: -------------------------------------------------------------------------------- 1 | 127.0.0.1 {{ inventory_hostname }} 2 | 127.0.1.1 {{ inventory_hostname }} 3 | 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 4 | ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 5 | 6 | 7 | {% for host in play_hosts %} 8 | {% if 'ansible_eth0' in hostvars[host] %} 9 | {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }} {{ host }} 10 | {% else %} 11 | {{ hostvars[host]['ansible_default_ipv4'] }} {{ host }} 12 | {% endif %} 13 | {% endfor %} 14 | -------------------------------------------------------------------------------- /molecule/default/host_vars/test-multi-01.yml: -------------------------------------------------------------------------------- 1 | --- 2 | mongo_thp: false 3 | mongo_numa: false 4 | 5 | mongo_admin_pass: something 6 | mongo_adminuser_pass: something 7 | 8 | mongo_user: 9 | - database: burgers 10 | name: bob 11 | password: 12345 12 | state: present 13 | update_password: on_create 14 | 15 | mongo_backup: 16 | enabled: true 17 | dbs: 18 | - admin 19 | - config 20 | - local 21 | user: backup 22 | pass: something 23 | path: /var/lib/mongo_backups 24 | owner: mongod 25 | group: mongod 26 | mode: '0660' 27 | hour: 2 28 | minute: 5 29 | day: "*" 30 | retention: 46 # in hours 31 | -------------------------------------------------------------------------------- /molecule/cluster/converge.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # required for fact gathering, ipv4 address 3 | - name: Converge 4 | hosts: 5 | - test-multi-01 6 | - test-multi-02 7 | - test-multi-03 8 | tasks: 9 | - name: install iproute 10 | dnf: 11 | name: iproute 12 | 13 | - name: set /etc/hosts file 14 | template: 15 | src: hosts.j2 16 | dest: /etc/hosts 17 | mode: '0644' 18 | owner: root 19 | group: root 20 | 21 | - name: Converge 22 | hosts: 23 | - test-multi-01 24 | - test-multi-02 25 | - test-multi-03 26 | any_errors_fatal: true 27 | roles: 28 | - ../ansible_role_mongodb 29 | -------------------------------------------------------------------------------- /molecule/default/molecule.yml: -------------------------------------------------------------------------------- 1 | --- 2 | lint: | 3 | set -e 4 | yamllint . 5 | ansible-lint 6 | scenario: 7 | name: default 8 | dependency: 9 | name: galaxy 10 | driver: 11 | name: docker 12 | provisioner: 13 | name: ansible 14 | verifier: 15 | name: ansible 16 | platforms: 17 | - name: test-multi-01 18 | hostname: test-multi-01 19 | image: robertdebock/rockylinux 20 | pull: true 21 | command: "/usr/sbin/init" # to use systemd 22 | volumes: 23 | - "/sys/fs/cgroup:/sys/fs/cgroup:ro" 24 | tmpfs: 25 | - /run 26 | - /tmp 27 | tty: true 28 | privileged: true 29 | environment: 30 | container: docker 31 | pre_build_image: true 32 | networks: 33 | - name: test_network 34 | -------------------------------------------------------------------------------- /molecule/cluster/group_vars/all.yml: -------------------------------------------------------------------------------- 1 | --- 2 | mongo_restart_config: true 3 | mongo_restart_seconds: 5 4 | 5 | mongo_thp: false 6 | mongo_numa: false 7 | 8 | mongo_replication: 9 | replSetName: something 10 | 11 | mongo_security: 12 | authorization: enabled 13 | keyFile: /etc/keyfile_mongo 14 | 15 | mongo_admin_pass: something 16 | mongo_adminuser_pass: something 17 | 18 | mongo_net: 19 | bindIp: 0.0.0.0 20 | port: 27018 21 | 22 | mongo_systemlog: 23 | destination: file 24 | logAppend: true 25 | path: /opt/somewhere/mongod.log 26 | 27 | mongo_storage: 28 | dbPath: /opt/mongo/ 29 | journal: 30 | enabled: true 31 | 32 | mongo_user: 33 | - database: burgers 34 | name: bob 35 | password: 12345 36 | state: present 37 | update_password: on_create 38 | -------------------------------------------------------------------------------- /templates/mongod_init.conf.j2: -------------------------------------------------------------------------------- 1 | # mongod.conf 2 | 3 | # temporary file, for initial setup 4 | 5 | security: 6 | authorization: disabled 7 | 8 | systemLog: 9 | {{ mongo_systemlog | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 10 | 11 | storage: 12 | dbPath: {{ mongo_storage.dbPath }} 13 | {% if mongo_version <= 6.0 -%} 14 | journal: 15 | enabled: true 16 | {% endif %} 17 | 18 | processManagement: 19 | fork: true 20 | pidFilePath: /var/run/mongodb/mongod.pid 21 | timeZoneInfo: /usr/share/zoneinfo 22 | 23 | net: 24 | port: {{ mongo_net.port }} 25 | bindIp: {{ mongo_net.bindIp }} 26 | 27 | {% if replication_init is defined and replication_init %} 28 | replication: 29 | {{ mongo_replication | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 30 | {% endif %} 31 | -------------------------------------------------------------------------------- /tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # this reset playbook is meant for development, thus commented out by design 3 | # - include_tasks: reset.yml 4 | 5 | # Do not skip, it is required 6 | - include_tasks: assert.yml 7 | 8 | - include_tasks: install.yml 9 | 10 | - include_tasks: thp.yml 11 | when: mongo_thp 12 | 13 | - include_tasks: numa.yml 14 | when: mongo_numa 15 | 16 | - include_tasks: keyfile.yml 17 | when: 18 | - host_count != '1' 19 | - mongo_security.keyFile is defined 20 | 21 | - include_tasks: user_init.yml 22 | when: set_user.changed 23 | 24 | - include_tasks: cluster.yml 25 | when: host_count != '1' 26 | 27 | - include_tasks: config.yml 28 | 29 | - include_tasks: user.yml 30 | when: 31 | - mongo_user | length > 0 32 | - host_count == '1' or mongo_primary 33 | 34 | - include_tasks: backup.yml 35 | when: mongo_backup.enabled 36 | -------------------------------------------------------------------------------- /tasks/numa.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: numa | install numactl 3 | dnf: 4 | name: numactl 5 | 6 | - name: numa | check zone reclaim mode 7 | shell: cat /proc/sys/vm/zone_reclaim_mode 8 | register: zone_reclaim_check 9 | changed_when: false 10 | 11 | - name: numa | apply changes when required 12 | shell: "{{ item }}" 13 | when: zone_reclaim_check.stdout != '0' 14 | loop: 15 | - echo 0 | sudo tee /proc/sys/vm/zone_reclaim_mode 16 | - sysctl -w vm.zone_reclaim_mode=0 17 | 18 | - name: numa | service file 19 | lineinfile: 20 | path: /usr/lib/systemd/system/mongod.service 21 | regexp: '^ExecStart=' 22 | line: "ExecStart=/usr/bin/numactl --interleave=all /usr/bin/mongod $OPTIONS" 23 | register: numa_service_file 24 | 25 | - name: numa | reload daemons, because a service file changed 26 | systemd: 27 | daemon_reload: true 28 | when: numa_service_file.changed 29 | -------------------------------------------------------------------------------- /tasks/user_init.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: user_init | set temporary conf 3 | template: 4 | src: mongod_init.conf.j2 5 | dest: /etc/mongod.conf 6 | owner: root 7 | group: root 8 | mode: '0644' 9 | 10 | - name: user_init | start mongo 11 | service: 12 | name: mongod 13 | state: started 14 | 15 | - name: user_init | create users admin, adminuser and backup 16 | community.mongodb.mongodb_user: 17 | database: admin 18 | name: "{{ item.name }}" 19 | password: "{{ item.pass }}" 20 | roles: "{{ item.role }}" 21 | login_host: 127.0.0.1 22 | login_port: "{{ mongo_net.port }}" 23 | # no_log: true 24 | loop: 25 | - name: admin 26 | pass: "{{ mongo_admin_pass }}" 27 | role: root 28 | - name: "{{ mongo_adminuser_name }}" 29 | pass: "{{ mongo_adminuser_pass }}" 30 | role: userAdminAnyDatabase 31 | - name: "{{ mongo_backup.user }}" 32 | pass: "{{ mongo_backup.pass }}" 33 | role: backup 34 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | image: docker:latest 3 | 4 | services: 5 | - name: docker:dind 6 | entrypoint: ["env", "-u", "DOCKER_HOST"] 7 | command: ["dockerd-entrypoint.sh"] 8 | 9 | variables: 10 | DOCKER_DRIVER: overlay2 11 | DOCKER_TLS_CERTDIR: "/certs" 12 | 13 | stages: 14 | - test 15 | 16 | before_script: 17 | - docker info 18 | - rm -rf "/var/cache/apk/*" 19 | - apk -U upgrade && apk update 20 | - apk add libffi-dev openssl-dev musl-dev libressl-dev build-base make gcc 21 | - apk add python3 python3-dev py3-pip py3-cryptography 22 | 23 | molecule: 24 | stage: test 25 | tags: 26 | - docker 27 | script: 28 | - docker -v 29 | - python3 -V 30 | - python3 -m pip install ansible ansible-lint 31 | - python3 -m pip install flake8 molecule yamllint requests 32 | - python3 -m pip install docker docker-compose 33 | - python3 -m pip install "molecule[docker]" 34 | - ansible --version 35 | - molecule --version 36 | - molecule test -s default 37 | - molecule test -s cluster 38 | except: 39 | changes: 40 | - README.md 41 | -------------------------------------------------------------------------------- /tasks/user.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: user | set defined users and databases 3 | community.mongodb.mongodb_user: 4 | login_host: localhost 5 | login_port: "{{ mongo_net.port }}" 6 | login_database: admin 7 | login_user: admin 8 | login_password: "{{ mongo_admin_pass }}" 9 | 10 | database: "{{ item.database }}" 11 | name: "{{ item.name }}" 12 | roles: "{{ item.roles | default(omit) }}" 13 | password: "{{ item.password }}" 14 | update_password: "{{ item.update_password | default('always') }}" 15 | state: "{{ item.state | default(present) }}" 16 | 17 | replica_set: "{{ mongo_replication.replSet | default(omit) }}" 18 | 19 | ssl: "{{ item.ssl | default(omit) }}" 20 | ssl_ca_certs: "{{ item.ca_certs | default(omit) }}" 21 | ssl_cert_reqs: "{{ item.cert_reqs | default(omit) }}" 22 | ssl_certfile: "{{ item.certfile | default(omit) }}" 23 | ssl_crlfile: "{{ item.ssl_crlfile | default(omit) }}" 24 | ssl_keyfile: "{{ item.ssl_keyfile | default(omit) }}" 25 | ssl_pem_passphrase: "{{ item.ssl_pem_passphrase | default(omit) }}" 26 | 27 | auth_mechanism: "{{ item.auth_mechanism | default(omit) }}" 28 | connection_options: "{{ item.connection_options | default(omit) }}" 29 | create_for_localhost_exception: >- 30 | {{ item.create_for_localhost_exception | default(omit) }} 31 | loop: "{{ mongo_user }}" 32 | -------------------------------------------------------------------------------- /tasks/reset.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # This playbook is for development purposes. 3 | # It simply removes all mongo related files quick 'n dirty 4 | # This is configured to 'quickly' start with a fresh setup again 5 | 6 | - name: reset | repo gpg key 7 | rpm_key: 8 | key: https://www.mongodb.org/static/pgp/server-{{ mongo_version }}.asc 9 | state: absent 10 | 11 | - name: reset | remove mongo from system 12 | shell: "{{ item }}" 13 | loop: 14 | - "rm -f /etc/yum.repos.d/mongodb.repo" 15 | - "yum remove mongod* -y" 16 | - "rm -rf /etc/mongo*" 17 | - "rm -rf /var/lib/mongo*" 18 | - "rm -rf /var/log/mongo*" 19 | - "rm -rf {{ mongo_systemlog.path }}" 20 | - "rm -rf {{ mongo_storage.dbPath }}" 21 | - "rm {{ mongo_security.keyFile | default(omit) }} | echo" 22 | - "rm -f /etc/systemd/system/disable-transparent-hugepage*" 23 | - userdel mongod | echo 24 | - rm -rf /etc/tuned/virtual-guest-no-thp/tuned.conf 25 | - "rm -rf {{ mongo_backup.path }}" 26 | - userdel mongod | echo # weird bug, but sometimes the user isn't removed 27 | - "rm -f /usr/lib/systemd/system/mongod.service" 28 | when: true 29 | 30 | - name: reset | remove backup scripts 31 | cron: 32 | name: "{{ item }}" 33 | state: absent 34 | loop: 35 | - 'remove mongodb old backup files' 36 | - 'create backup of mongo' 37 | 38 | - name: reset | reload daemons 39 | systemd: 40 | daemon_reload: true 41 | -------------------------------------------------------------------------------- /molecule/cluster/molecule.yml: -------------------------------------------------------------------------------- 1 | --- 2 | lint: | 3 | set -e 4 | yamllint . 5 | ansible-lint 6 | scenario: 7 | name: cluster 8 | dependency: 9 | name: galaxy 10 | driver: 11 | name: docker 12 | provisioner: 13 | name: ansible 14 | verifier: 15 | name: ansible 16 | platforms: 17 | - name: test-multi-01 18 | hostname: test-multi-01 19 | image: robertdebock/rockylinux 20 | pull: true 21 | command: "/usr/sbin/init" 22 | volumes: 23 | - "/sys/fs/cgroup:/sys/fs/cgroup:ro" 24 | tmpfs: 25 | - /run 26 | - /tmp 27 | tty: true 28 | environment: 29 | container: docker 30 | pre_build_image: true 31 | networks: 32 | - name: test_network 33 | - name: test-multi-02 34 | hostname: test-multi-02 35 | image: robertdebock/rockylinux 36 | pull: true 37 | command: "/usr/sbin/init" 38 | volumes: 39 | - "/sys/fs/cgroup:/sys/fs/cgroup:ro" 40 | tmpfs: 41 | - /run 42 | - /tmp 43 | tty: true 44 | environment: 45 | container: docker 46 | pre_build_image: true 47 | networks: 48 | - name: test_network 49 | - name: test-multi-03 50 | hostname: test-multi-03 51 | image: robertdebock/rockylinux 52 | pull: true 53 | command: "/usr/sbin/init" 54 | volumes: 55 | - "/sys/fs/cgroup:/sys/fs/cgroup:ro" 56 | tmpfs: 57 | - /run 58 | - /tmp 59 | tty: true 60 | environment: 61 | container: docker 62 | pre_build_image: true 63 | networks: 64 | - name: test_network 65 | -------------------------------------------------------------------------------- /tasks/thp.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: thp | install tuned 3 | dnf: 4 | name: tuned 5 | 6 | - name: thp | tuned dir 7 | file: 8 | path: /etc/tuned/virtual-guest-no-thp 9 | state: directory 10 | owner: root 11 | group: root 12 | mode: '0755' 13 | 14 | - name: thp | tuned conf file 15 | template: 16 | src: tuned.j2 17 | dest: /etc/tuned/virtual-guest-no-thp/tuned.conf 18 | owner: root 19 | group: root 20 | mode: '0644' 21 | register: tuned_conf 22 | 23 | - name: thp | enable tuned profile 24 | shell: tuned-adm profile virtual-guest-no-thp 25 | when: tuned_conf.changed 26 | 27 | - name: thp | check transparent hugepages in kernel 28 | shell: cat /sys/kernel/mm/transparent_hugepage/enabled 29 | changed_when: false 30 | register: check_hugepages 31 | 32 | - name: thp | load tuned-adm profile in kernel 33 | shell: /sbin/tuned-adm profile no-thp 34 | when: "'[always] madvise never' in check_hugepages.stdout" 35 | 36 | - name: thp | set service file 37 | template: 38 | src: disable-transparent-hugepages.service.j2 39 | dest: /etc/systemd/system/disable-transparent-hugepages.service 40 | owner: root 41 | group: root 42 | mode: '0644' 43 | register: set_service_file 44 | 45 | - name: thp | reload daemons, because a service file changed 46 | systemd: 47 | daemon_reload: true 48 | when: set_service_file.changed 49 | 50 | - name: thp | enable and start transparent hugepages when set 51 | service: 52 | name: disable-transparent-hugepages 53 | enabled: true 54 | -------------------------------------------------------------------------------- /tasks/config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: conf | set 3 | template: 4 | src: mongod.conf.j2 5 | dest: /etc/mongod.conf 6 | owner: root 7 | group: root 8 | mode: '0644' 9 | register: mongo_conf_set 10 | 11 | - name: conf | ensure mongod is started and enabled 12 | service: 13 | name: mongod 14 | state: started 15 | enabled: true 16 | 17 | - name: conf | restart mongod service one by one, after a config change, if set 18 | shell: "systemctl restart mongod && sleep {{ mongo_restart_seconds }}" 19 | run_once: true 20 | delegate_to: "{{ item }}" 21 | loop: "{{ ansible_play_hosts }}" 22 | when: 23 | - mongo_restart_config 24 | - mongo_conf_set.changed 25 | 26 | - name: conf | check cluster health after config change if applicable 27 | community.mongodb.mongodb_status: 28 | login_host: localhost 29 | login_port: "{{ mongo_net.port }}" 30 | login_user: admin 31 | login_password: "{{ mongo_admin_pass }}" 32 | validate: minimal 33 | poll: 5 34 | interval: 12 35 | replica_set: "{{ mongo_replication.replSetName }}" 36 | 37 | ssl: "{{ item.ssl | default(omit) }}" 38 | ssl_ca_certs: "{{ item.ca_certs | default(omit) }}" 39 | ssl_cert_reqs: "{{ item.cert_reqs | default(omit) }}" 40 | ssl_certfile: "{{ item.certfile | default(omit) }}" 41 | ssl_crlfile: "{{ item.ssl_crlfile | default(omit) }}" 42 | ssl_keyfile: "{{ item.ssl_keyfile | default(omit) }}" 43 | ssl_pem_passphrase: "{{ item.ssl_pem_passphrase | default(omit) }}" 44 | 45 | auth_mechanism: "{{ item.auth_mechanism | default(omit) }}" 46 | connection_options: "{{ item.connection_options | default(omit) }}" 47 | create_for_localhost_exception: >- 48 | {{ item.create_for_localhost_exception | default(omit) }} 49 | when: 50 | - host_count != '1' 51 | - mongo_restart_config 52 | - mongo_conf_set.changed 53 | - mongo_primary 54 | -------------------------------------------------------------------------------- /tasks/backup.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: backup | set fact for first secondary in play 3 | set_fact: 4 | backup_on_host: "{{ item }}" 5 | loop: "{{ play_hosts }}" 6 | when: 7 | - host_count != '1' 8 | - backup_on_host is undefined 9 | - hostvars[item].mongo_replication_role == 'secondary' 10 | run_once: true 11 | 12 | - block: 13 | 14 | - name: backup | ensure backup path exists 15 | file: 16 | path: "{{ mongo_backup.path }}" 17 | owner: "{{ mongo_backup.owner }}" 18 | group: "{{ mongo_backup.group }}" 19 | mode: "{{ mongo_backup.mode }}" 20 | state: 'directory' 21 | 22 | - name: backup | set job in cron 23 | cron: 24 | name: "{{ item.name }}" 25 | minute: "{{ mongo_backup.minute }}" 26 | hour: "{{ mongo_backup.hour }}" 27 | day: "{{ mongo_backup.day }}" 28 | job: "{{ item.job }}" 29 | no_log: true 30 | loop: 31 | - name: 'remove mongodb old backup files' 32 | minute: "{{ mongo_backup.minute | int - 1 }}" 33 | job: "/usr/bin/find {{ mongo_backup.path }}/ -maxdepth 1 -type d 34 | -mmin +$((60*{{ mongo_backup.retention }})) -exec rm -rf {} \\+" 35 | 36 | - name: 'create backup of mongo' 37 | minute: "{{ mongo_backup.minute }}" 38 | job: "for dbs in {{ mongo_backup.dbs | join(' ') }} ; do 39 | mongodump --out 40 | {{ mongo_backup.path }}/mongo_backup_$(date '+\\%Y-\\%m-\\%d') 41 | --db $dbs 42 | --port {{ mongo_net.port }} 43 | --authenticationDatabase admin 44 | --username '{{ mongo_backup.user }}' 45 | --password '{{ mongo_backup.pass }}' 46 | && ln -sf 47 | {{ mongo_backup.path }}/mongo_backup_$(date '+\\%Y-\\%m-\\%d') 48 | {{ mongo_backup.path }}/latest ; done" 49 | 50 | when: >- 51 | host_count == '1' or 52 | backup_on_host is defined and inventory_hostname == backup_on_host 53 | -------------------------------------------------------------------------------- /defaults/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | mongo_repo: true 3 | mongo_version: 5.0 4 | mongo_edition: org # org or enterprise 5 | mongo_pymongo_version: 4.7.2 6 | 7 | # Apply production recommendations, see readme 8 | mongo_thp: true 9 | mongo_numa: true 10 | 11 | mongo_admin_pass: 'change_me' 12 | mongo_adminuser_name: adminuser 13 | mongo_adminuser_pass: 'change_me' 14 | 15 | # --- Defaults for mongod.conf 16 | # See readme 17 | 18 | mongo_net: 19 | bindIp: 0.0.0.0 20 | port: 27017 21 | 22 | mongo_systemlog: 23 | destination: file 24 | logAppend: true 25 | path: /var/log/mongodb/mongod.log 26 | 27 | mongo_storage: 28 | dbPath: /var/lib/mongo 29 | journal: 30 | enabled: true 31 | 32 | # You should not change the pidfile location 33 | mongo_processmanagement: 34 | fork: true 35 | pidFilePath: /var/run/mongodb/mongod.pid 36 | timeZoneInfo: /usr/share/zoneinfo 37 | 38 | # The keyfile is automatically generated 39 | mongo_security: '' 40 | 41 | mongo_operationprofiling: '' 42 | 43 | mongo_replication: '' 44 | 45 | mongo_sharding: '' 46 | 47 | mongo_auditlog: '' 48 | 49 | mongo_snmp: '' 50 | 51 | mongo_custom_cnf: '' 52 | 53 | # --- 54 | 55 | # When replication is desired, the value should either be 56 | # primary, secondary or aribter 57 | # Ensure to include a valid number of nodes, see readme 58 | mongo_replication_role: '' 59 | 60 | # Define databases and users 61 | # See readme for examples 62 | mongo_user: [] 63 | 64 | # Backup via cronjob, executed with mongodump 65 | # When there is replication, only active on one secondary 66 | mongo_backup: 67 | enabled: true 68 | dbs: 69 | - admin 70 | - config 71 | - local 72 | user: backup 73 | pass: change_me 74 | path: /var/lib/mongo_backups 75 | owner: mongod 76 | group: mongod 77 | mode: '0660' 78 | hour: 2 79 | minute: 5 80 | day: "*" 81 | retention: 46 # in hours 82 | 83 | # Restart mongo after a config change 84 | mongo_restart_config: true 85 | 86 | # Amount of seconds before the next mongo instance will be restarted 87 | mongo_restart_seconds: 15 88 | -------------------------------------------------------------------------------- /templates/mongod.conf.j2: -------------------------------------------------------------------------------- 1 | # mongod.conf 2 | 3 | {{ ansible_managed | comment }} 4 | 5 | # for documentation of all options, see: 6 | # http://docs.mongodb.org/manual/reference/configuration-options/ 7 | 8 | systemLog: 9 | {{ mongo_systemlog | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 10 | 11 | storage: 12 | {{ mongo_storage | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 13 | 14 | processManagement: 15 | {{ mongo_processmanagement | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 16 | 17 | net: 18 | {{ mongo_net | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 19 | 20 | {% if mongo_security != '' %} 21 | security: 22 | {{ mongo_security | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 23 | {% else %} 24 | #security: 25 | {% endif %} 26 | 27 | {% if mongo_operationprofiling != '' %} 28 | operationProfiling: 29 | {{ mongo_operationprofiling | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 30 | {% else %} 31 | #operationProfiling: 32 | {% endif %} 33 | 34 | {% if mongo_replication != '' %} 35 | replication: 36 | {{ mongo_replication | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 37 | {% else %} 38 | #replication: 39 | {% endif %} 40 | 41 | {% if mongo_sharding != '' %} 42 | sharding: 43 | {{ mongo_sharding | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 44 | {% else %} 45 | #sharding: 46 | {% endif %} 47 | 48 | ## Enterprise-Only Options 49 | {% if mongo_auditlog != '' %} 50 | auditLog: 51 | {{ mongo_auditlog | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 52 | {% else %} 53 | #auditLog: 54 | {% endif %} 55 | 56 | {% if mongo_snmp != '' %} 57 | snmp: 58 | {{ mongo_snmp | to_nice_yaml(indent=2) | indent(width=2, first=True) }} 59 | {% else %} 60 | #snmp: 61 | {% endif %} 62 | 63 | {% if mongo_custom_cnf != '' %} 64 | {% for section_name, section_contents in mongo_custom_cnf.items() %} 65 | {{ section_name }}: 66 | {% for key, value in section_contents.items() %} 67 | {% if value is defined and value %} 68 | {{ key }}: {{ value }} 69 | {% else %} 70 | {{ key }} 71 | {% endif %} 72 | {% endfor %} 73 | {% endfor %} 74 | {% endif %} 75 | -------------------------------------------------------------------------------- /tasks/assert.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: assert | set fact for amount of hosts 3 | set_fact: 4 | host_count: "{{ ansible_play_hosts | length }}" 5 | 6 | - name: assert | that uneven amount of hosts are set 7 | assert: 8 | that: "{{ host_count | int % 2 != 0 }}" 9 | 10 | - name: assert | that naming is set correctly for replication roles 11 | assert: 12 | that: | 13 | mongo_replication_role == 'arbiter' or 14 | mongo_replication_role == 'secondary' or 15 | mongo_replication_role == 'primary' 16 | when: host_count != '1' 17 | 18 | - name: assert | set fact for roles 19 | set_fact: 20 | mongo_primary: "{{ mongo_replication_role == 'primary' }}" 21 | mongo_secondary: "{{ mongo_replication_role == 'secondary' }}" 22 | mongo_arbiter: "{{ mongo_replication_role == 'arbiter' }}" 23 | 24 | - name: assert | several items for a single host 25 | assert: 26 | that: 27 | - mongo_replication_role == '' 28 | - mongo_security.keyFile is not defined 29 | when: host_count == '1' 30 | 31 | - name: assert | that passwords are changed 32 | assert: 33 | that: 34 | - mongo_admin_pass != 'change_me' 35 | - mongo_adminuser_pass != 'change_me' 36 | - mongo_backup.pass != 'change_me' 37 | 38 | - block: 39 | 40 | - name: assert | create dictionary of bootstrappers 41 | set_fact: 42 | primaries: "{{ dict(keys|zip(values)) }}" 43 | vars: 44 | keys: "{{ ansible_play_hosts }}" 45 | values: "{{ ansible_play_hosts| 46 | map('extract', hostvars, ['mongo_primary']) | 47 | list }}" 48 | 49 | - name: assert | create list of bootstrappers 50 | set_fact: 51 | primary_list: "{{ primaries | dict2items | 52 | selectattr('value') | 53 | map(attribute='key') | 54 | list }}" 55 | 56 | - name: assert | that there is one primary 57 | assert: 58 | that: primary_list | length == 1 59 | 60 | - name: assert | create dictionary of bootstrappers 61 | set_fact: 62 | arbiters: "{{ dict(keys|zip(values)) }}" 63 | vars: 64 | keys: "{{ ansible_play_hosts }}" 65 | values: "{{ ansible_play_hosts| 66 | map('extract', hostvars, ['mongo_arbiter']) | 67 | list }}" 68 | 69 | - name: assert | create list of arbiters 70 | set_fact: 71 | arbiter_list: "{{ arbiters | dict2items | 72 | selectattr('value') | 73 | map(attribute='key') | 74 | list }}" 75 | 76 | - name: assert | that there is one or no arbiter 77 | assert: 78 | that: (arbiter_list | length == 1) or (arbiter_list | length == 0) 79 | 80 | - name: assert | several asserts for when cluster is enabled 81 | assert: 82 | that: 83 | - mongo_replication_role != '' 84 | - mongo_replication.replSetName | length > 0 85 | - mongo_security.keyFile | length > 0 86 | - mongo_primary is defined 87 | - mongo_secondary is defined 88 | 89 | run_once: true 90 | when: host_count != '1' 91 | -------------------------------------------------------------------------------- /tasks/keyfile.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: keyfile | set fact to copy keyfile from a host 3 | set_fact: 4 | keyfile_host: "{{ item }}" 5 | when: hostvars[item].mongo_primary 6 | run_once: true 7 | loop: "{{ ansible_play_hosts }}" 8 | 9 | - name: keyfile | stat 10 | stat: 11 | path: "{{ mongo_security.keyFile }}" 12 | register: keyfile_check 13 | 14 | - name: keyfile | set fact 15 | set_fact: 16 | keyfile_fact: "{{ keyfile_check.stat.exists }}" 17 | 18 | - name: keyfile | block to check which host(s) have the file 19 | block: 20 | 21 | - name: keyfile | create dict of keyfile check 22 | set_fact: 23 | keyfile_status: "{{ dict(keys|zip(values)) }}" 24 | vars: 25 | keys: "{{ ansible_play_hosts }}" 26 | values: "{{ ansible_play_hosts | 27 | map('extract', hostvars, ['keyfile_fact']) 28 | | list }}" 29 | 30 | - name: keyfile | set fact when no host has the file 31 | set_fact: 32 | keyfile_none: true 33 | when: keyfile_status.values() | list is not any 34 | 35 | - name: keyfile | set fact when a host does not has the file 36 | set_fact: 37 | keyfile_all: false 38 | when: keyfile_status.values() | list is any 39 | 40 | - name: keyfile | set fact when all hosts have the files 41 | set_fact: 42 | keyfile_all: true 43 | when: keyfile_status.values() | list is all 44 | 45 | run_once: true 46 | 47 | - name: keyfile | block to copy keyfile when none has one 48 | block: 49 | 50 | - name: keyfile | create when none has a keyfile 51 | shell: >- 52 | openssl rand -base64 741 > {{ mongo_security.keyFile }} ; 53 | chmod 400 {{ mongo_security.keyFile }} ; 54 | chown mongod: {{ mongo_security.keyFile }} 55 | register: new_keyfile 56 | when: mongo_primary 57 | 58 | - name: keyfile | fetch keyfile 59 | fetch: 60 | src: "{{ mongo_security.keyFile }}" 61 | flat: true 62 | dest: /tmp/mongo_keyfile 63 | delegate_to: "{{ keyfile_host }}" 64 | 65 | - name: keyfile | copy required files to remaining hosts 66 | copy: 67 | src: /tmp/mongo_keyfile 68 | dest: "{{ mongo_security.keyFile }}" 69 | mode: '0400' 70 | owner: mongod 71 | group: mongod 72 | 73 | when: keyfile_none is defined 74 | 75 | - name: keyfile | block to copy keyfile when at least one is missing 76 | block: 77 | 78 | - name: keyfile | fetch keyfile 79 | fetch: 80 | src: "{{ mongo_security.keyFile }}" 81 | flat: true 82 | dest: /tmp/mongo_keyfile 83 | delegate_to: "{{ keyfile_host }}" 84 | 85 | - name: keyfile | copy required files to remaining hosts 86 | copy: 87 | src: /tmp/mongo_keyfile 88 | dest: "{{ mongo_security.keyFile }}" 89 | mode: '0400' 90 | owner: mongod 91 | group: mongod 92 | 93 | when: keyfile_all is defined and not keyfile_all 94 | 95 | - name: keyfile | ensure absence from localhost 96 | file: 97 | path: /tmp/mongo_keyfile 98 | state: absent 99 | run_once: true 100 | delegate_to: localhost 101 | become: false 102 | -------------------------------------------------------------------------------- /tasks/install.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: install | repo gpg key 3 | rpm_key: 4 | key: https://www.mongodb.org/static/pgp/server-{{ mongo_version }}.asc 5 | when: mongo_repo 6 | 7 | - name: install | repo 8 | yum_repository: 9 | name: "mongodb-org-{{ mongo_version }}" 10 | description: 'MongoDB {{ mongo_edition }} repo' 11 | file: mongodb 12 | baseurl: >- 13 | https://repo.mongodb. 14 | {{- (mongo_edition == 'enterprise') | ternary('com', 'org') -}} 15 | /yum/redhat/$releasever/mongodb- 16 | {{- mongo_edition }}/ 17 | {{- mongo_version }}/x86_64/ 18 | enabled: true 19 | gpgcheck: true 20 | gpgkey: https://www.mongodb.org/static/pgp/server-{{ mongo_version }}.asc 21 | when: mongo_repo 22 | 23 | - name: install | group mongod 24 | group: 25 | name: mongod 26 | gid: 28 27 | system: true 28 | 29 | - name: install | user mongod 30 | user: 31 | name: mongod 32 | uid: 28 33 | system: true 34 | group: mongod 35 | comment: 'MongoDB Server' 36 | home: "{{ mongo_storage.dbPath }}" 37 | create_home: false 38 | shell: /sbin/nologin 39 | register: set_user 40 | 41 | - name: install | dependencies 42 | dnf: 43 | name: 44 | - python3-devel 45 | - python3-pip 46 | 47 | - name: install | mongo edition {{ mongo_edition }} 48 | dnf: 49 | name: mongodb-{{ mongo_edition }} 50 | 51 | - name: install | data folder 52 | file: 53 | state: directory 54 | path: "{{ mongo_storage.dbPath }}" 55 | mode: '0770' 56 | owner: mongod 57 | group: mongod 58 | 59 | - name: install | remove default data folder when set differently 60 | file: 61 | state: absent 62 | path: /var/lib/mongo 63 | when: mongo_storage.dbPath != '/var/lib/mongo' 64 | 65 | - name: install | remove log folder when set differently 66 | file: 67 | state: absent 68 | path: /var/log/mongodb 69 | when: >- 70 | '/var/log/mongodb' not in mongo_systemlog.path or 71 | mongo_systemlog.destination != 'file' 72 | 73 | - block: 74 | - name: install | ensure log folder exists 75 | file: 76 | path: "{{ mongo_systemlog.path | dirname }}" 77 | state: directory 78 | owner: mongod 79 | group: mongod 80 | mode: '0775' 81 | 82 | - name: install | stat if log file exist 83 | stat: 84 | path: "{{ mongo_systemlog.path }}" 85 | register: mongo_log_check 86 | 87 | - name: install | ensure log files exist 88 | copy: 89 | content: "" 90 | dest: "{{ mongo_systemlog.path }}" 91 | force: true 92 | group: mongod 93 | owner: mongod 94 | mode: '0755' 95 | when: not mongo_log_check.stat.exists 96 | 97 | when: >- 98 | '/var/log/mongodb' not in mongo_systemlog.path and 99 | mongo_systemlog.destination == 'file' 100 | 101 | - name: install | pymongo {{ mongo_pymongo_version }} 102 | pip: 103 | name: pymongo 104 | executable: pip3 105 | version: "{{ mongo_pymongo_version }}" 106 | 107 | # Check firewalld status 108 | - name: Populate service facts 109 | ansible.builtin.service_facts: 110 | 111 | - name: Open ports on firewall 112 | ansible.posix.firewalld: 113 | port: "{{ mongo_net.port }}/tcp" 114 | permanent: true 115 | immediate: true 116 | state: enabled 117 | when: ansible_facts['services']['firewalld.service']['state'] == 'running' 118 | -------------------------------------------------------------------------------- /tasks/cluster.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: cluster | check if hosts are in clustered 3 | shell: >- 4 | mongosh --port {{ mongo_net.port }} --quiet --eval 'db.isMaster().hosts' 5 | register: check_cluster 6 | changed_when: false 7 | 8 | # # Get the replicaset status and then lookup the primary 9 | # hostname and save to a variable 10 | # - name: Ensure replicaset is stable before beginning 11 | # community.mongodb.mongodb_status: 12 | # login_user: "{{ admin_user }}" 13 | # login_password: "{{ admin_user_password }}" 14 | # poll: 3 15 | # interval: 10 16 | # register: rs 17 | # 18 | # - name: Lookup PRIMARY replicaset member 19 | # set_fact: 20 | # primary: "{{ item.key.split('.')[0] }}" 21 | # loop: "{{ lookup('dict', rs.replicaset) }}" 22 | # when: "'PRIMARY' in item.value" 23 | 24 | - name: cluster | set fact 25 | set_fact: 26 | check_cluster: "{{ check_cluster.stdout }}" 27 | 28 | - block: 29 | - name: cluster | create dict of cluster check 30 | set_fact: 31 | all_cluster_check: "{{ dict(keys|zip(values)) }}" 32 | vars: 33 | keys: "{{ ansible_play_hosts }}" 34 | values: "{{ ansible_play_hosts | 35 | map('extract', hostvars, ['check_cluster']) 36 | | list }}" 37 | 38 | - name: cluster | set fact when no host is clustered 39 | set_fact: 40 | no_host_is_clustered: false 41 | when: all_cluster_check.values() | list is not any 42 | 43 | - name: cluster | set fact when a host is not clustered 44 | set_fact: 45 | all_cluster_status: false 46 | when: all_cluster_check.values() | list is any 47 | 48 | - name: cluster | set fact when all hosts are in cluster 49 | set_fact: 50 | all_cluster_status: true 51 | when: all_cluster_check.values() | list is all 52 | 53 | run_once: true 54 | 55 | - name: cluster | build member list 56 | set_fact: 57 | members: >- 58 | {{ 59 | members | default([]) + 60 | [{ 61 | 'host': hostvars[item].ansible_fqdn + ':{{ mongo_net.port }}', 62 | 'priority': member_weight[hostvars[item].mongo_replication_role] 63 | }] 64 | }} 65 | loop: "{{ ansible_play_hosts }}" 66 | run_once: true 67 | vars: 68 | member_weight: 69 | primary: 3 70 | secondary: 2 71 | arbiter: 1 72 | 73 | - name: cluster | set fact for arbiter index number 74 | set_fact: 75 | arbiter_index: "{{ hostid }}" 76 | when: hostvars[item].mongo_arbiter 77 | loop: "{{ ansible_play_hosts }}" 78 | loop_control: 79 | index_var: hostid 80 | 81 | - name: cluster | block to initial build the replica set 82 | block: 83 | 84 | - name: cluster | set fact for initial replication 85 | set_fact: 86 | replication_init: true 87 | 88 | - name: cluster | set temporary conf 89 | template: 90 | src: mongod_init.conf.j2 91 | dest: /etc/mongod.conf 92 | owner: root 93 | group: root 94 | mode: '0644' 95 | 96 | - name: cluster | restart mongo 97 | service: 98 | name: mongod 99 | state: restarted 100 | 101 | - name: cluster | initial build 102 | community.mongodb.mongodb_replicaset: 103 | login_host: localhost 104 | login_port: "{{ mongo_net.port }}" 105 | login_user: admin 106 | login_password: "{{ mongo_admin_pass }}" 107 | replica_set: "{{ mongo_replication.replSetName }}" 108 | members: "{{ members }}" 109 | arbiter_at_index: "{{ arbiter_index | default(omit) }}" 110 | when: mongo_primary 111 | 112 | - name: cluster | wait until cluster health is ok 113 | community.mongodb.mongodb_status: 114 | login_port: "{{ mongo_net.port }}" 115 | validate: default 116 | poll: 5 117 | interval: 12 118 | replica_set: "{{ mongo_replication.replSetName }}" 119 | when: mongo_primary 120 | 121 | - name: cluster | place original config 122 | template: 123 | src: mongod.conf.j2 124 | dest: /etc/mongod.conf 125 | owner: root 126 | group: root 127 | mode: '0644' 128 | 129 | - name: cluster | restart mongod service one by one 130 | shell: "systemctl restart mongod && sleep {{ mongo_restart_seconds }}" 131 | run_once: true 132 | delegate_to: "{{ item }}" 133 | loop: "{{ ansible_play_hosts }}" 134 | 135 | - name: cluster | wait until cluster health is ok 136 | community.mongodb.mongodb_status: 137 | login_host: localhost 138 | login_port: "{{ mongo_net.port }}" 139 | login_user: admin 140 | login_password: "{{ mongo_admin_pass }}" 141 | validate: minimal 142 | poll: 5 143 | interval: 12 144 | replica_set: "{{ mongo_replication.replSetName }}" 145 | when: mongo_primary 146 | 147 | when: no_host_is_clustered is defined 148 | 149 | # - name: cluster | include scale playbook when applicable 150 | # include_tasks: scale.yml 151 | # when: 152 | # - all_cluster_status is defined and not all_cluster_status 153 | # - no_host_is_clustered is not defined 154 | -------------------------------------------------------------------------------- /playbooks/update.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: one_host 3 | become: true 4 | gather_facts: false 5 | tasks: 6 | - name: update | set fact for amount of hosts 7 | set_fact: 8 | host_count: "{{ ansible_play_hosts | length }}" 9 | 10 | - name: update | mongo edition {{ mongo_edition }} when one host is present 11 | dnf: 12 | name: "mongodb-{{ mongo_edition }}" 13 | state: latest 14 | when: host_count == '1' 15 | 16 | - name: update | set config 17 | template: 18 | src: mongod.conf.j2 19 | dest: /etc/mongod.conf 20 | owner: root 21 | group: root 22 | mode: '0644' 23 | 24 | - name: update | ensure mongod is started and enabled 25 | service: 26 | name: mongod 27 | state: started 28 | enabled: true 29 | 30 | - hosts: 31 | - mongo_arbiter 32 | - mongo_primary 33 | become: true 34 | any_errors_fatal: true 35 | gather_facts: false 36 | tasks: 37 | - name: update | set fact for roles 38 | set_fact: 39 | mongo_primary: "{{ mongo_replication_role == 'primary' }}" 40 | mongo_arbiter: "{{ mongo_replication_role == 'arbiter' }}" 41 | 42 | - name: update | ensure cluster health is ok 43 | community.mongodb.mongodb_status: 44 | login_host: localhost 45 | login_port: "{{ mongo_net.port }}" 46 | login_user: admin 47 | login_password: "{{ mongo_admin_pass }}" 48 | validate: minimal 49 | poll: 5 50 | interval: 12 51 | replica_set: "{{ mongo_replication.replSetName }}" 52 | when: mongo_primary 53 | 54 | - name: update | stop mongod on arbiter 55 | service: 56 | name: mongod 57 | state: stopped 58 | when: mongo_arbiter 59 | 60 | - name: update | mongo on arbiter 61 | dnf: 62 | name: "mongodb-{{ mongo_edition }}" 63 | state: latest 64 | when: mongo_arbiter 65 | 66 | - name: update | set config on arbiter 67 | template: 68 | src: mongod.conf.j2 69 | dest: /etc/mongod.conf 70 | owner: root 71 | group: root 72 | mode: '0644' 73 | when: mongo_arbiter 74 | 75 | - name: update | ensure mongod is started and enabled on arbiter 76 | service: 77 | name: mongod 78 | state: started 79 | enabled: true 80 | when: mongo_arbiter 81 | 82 | - name: update | pause 20s after a restart of mongo 83 | pause: 84 | seconds: '20' 85 | when: mongo_arbiter 86 | 87 | - name: update | ensure cluster health is ok 88 | community.mongodb.mongodb_status: 89 | login_host: localhost 90 | login_port: "{{ mongo_net.port }}" 91 | login_user: admin 92 | login_password: "{{ mongo_admin_pass }}" 93 | validate: minimal 94 | poll: 5 95 | interval: 12 96 | replica_set: "{{ mongo_replication.replSetName }}" 97 | when: mongo_primary 98 | 99 | - hosts: 100 | - mongo_primary 101 | - mongo_secondary 102 | serial: 1 103 | become: true 104 | any_errors_fatal: true 105 | gather_facts: false 106 | tasks: 107 | - name: update | set fact for roles 108 | set_fact: 109 | mongo_primary: "{{ mongo_replication_role == 'primary' }}" 110 | mongo_secondary: "{{ mongo_replication_role == 'secondary' }}" 111 | 112 | - name: update | ensure cluster health is ok 113 | community.mongodb.mongodb_status: 114 | login_host: localhost 115 | login_port: "{{ mongo_net.port }}" 116 | login_user: admin 117 | login_password: "{{ mongo_admin_pass }}" 118 | validate: minimal 119 | poll: 5 120 | interval: 12 121 | replica_set: "{{ mongo_replication.replSetName }}" 122 | when: mongo_primary 123 | 124 | - name: update | stop mongod on a secondary 125 | service: 126 | name: mongod 127 | state: stopped 128 | when: mongo_secondary 129 | 130 | - name: update | mongo on secondary 131 | dnf: 132 | name: "mongodb-{{ mongo_edition }}" 133 | state: latest 134 | when: mongo_secondary 135 | 136 | - name: update | set config on secondary 137 | template: 138 | src: mongod.conf.j2 139 | dest: /etc/mongod.conf 140 | owner: root 141 | group: root 142 | mode: '0644' 143 | when: mongo_secondary 144 | 145 | - name: update | ensure mongod is started and enabled on secondary 146 | service: 147 | name: mongod 148 | state: started 149 | enabled: true 150 | when: mongo_secondary 151 | 152 | - name: update | pause 20s after a restart of 153 | pause: 154 | seconds: '20' 155 | 156 | - name: update | ensure cluster health is ok 157 | community.mongodb.mongodb_status: 158 | login_host: localhost 159 | login_port: "{{ mongo_net.port }}" 160 | 161 | login_password: "{{ mongo_admin_pass }}" 162 | validate: minimal 163 | poll: 5 164 | interval: 12 165 | replica_set: "{{ mongo_replication.replSetName }}" 166 | when: mongo_primary 167 | 168 | - hosts: mongo_primary 169 | become: true 170 | any_errors_fatal: true 171 | gather_facts: false 172 | tasks: 173 | - name: update | set fact for roles 174 | set_fact: 175 | mongo_primary: "{{ mongo_replication_role == 'primary' }}" 176 | 177 | - name: update | copy step content 178 | copy: 179 | dest: /root/mongo_primary_stepdown.js 180 | mode: '0770' 181 | owner: root 182 | group: root 183 | content: | 184 | use admin; 185 | 186 | db.auth("admin", "{{ mongo_admin_pass }}"); 187 | 188 | db.adminCommand( { 189 | replSetStepDown: 60, 190 | secondaryCatchUpPeriodSecs: 30, 191 | force: false 192 | } ) 193 | register: set_primary_stepdown 194 | 195 | - name: update | make primary a secondary 196 | shell: mongo < /root/mongo_primary_stepdown.js 197 | when: set_primary_stepdown.changed 198 | 199 | - name: update | remove stepdown file 200 | file: 201 | state: absent 202 | path: /root/mongo_primary_stepdown.js 203 | 204 | - name: update | mongo on primary 205 | dnf: 206 | name: "mongodb-{{ mongo_edition }}" 207 | state: latest 208 | 209 | - name: update | set config on primary 210 | template: 211 | src: mongod.conf.j2 212 | dest: /etc/mongod.conf 213 | owner: root 214 | group: root 215 | mode: '0644' 216 | 217 | - name: update | ensure mongod is started and enabled on primary 218 | service: 219 | name: mongod 220 | state: started 221 | enabled: true 222 | 223 | - name: update | pause 20s after a restart of 224 | pause: 225 | seconds: '20' 226 | 227 | - name: update | ensure cluster health is ok 228 | community.mongodb.mongodb_status: 229 | login_host: localhost 230 | login_port: "{{ mongo_net.port }}" 231 | login_user: admin 232 | login_password: "{{ mongo_admin_pass }}" 233 | validate: minimal 234 | poll: 5 235 | interval: 12 236 | replica_set: "{{ mongo_replication.replSetName }}" 237 | -------------------------------------------------------------------------------- /tasks/scale.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # Still in development... 3 | # It is not easy to configure scaling in mongo with Ansible 4 | 5 | # The steps should be: 6 | # - If arbiter is present in configuration and on system 7 | # - remove arbiter from cluster 8 | # - Add new secondary or secondaries 9 | # - Add arbiter if configured 10 | 11 | # I have tried configuring this countless amount of times, but always failed 12 | # for some reason. I decided to not include scaling for now. 13 | 14 | 15 | # - name: scale | check if hosts are in cluster 16 | # shell: mongo --quiet --eval 'db.isMaster().hosts' 17 | # register: check_cluster 18 | # changed_when: false 19 | # 20 | # - name: scale | check if there are arbiters in the cluster 21 | # shell: mongo --quiet --eval 'db.isMaster().arbiters' 22 | # register: check_arbiters 23 | # 24 | # - name: scale | set fact to run tasks on primary 25 | # set_fact: 26 | # run_on: "{{ item }}" 27 | # with_items: "{{ play_hosts }}" 28 | # when: run_on is undefined and hostvars[item].mongo_primary 29 | # run_once: true 30 | # 31 | # - block: 32 | # 33 | # - name: assert | create dictionary of arbiters 34 | # set_fact: 35 | # arb_check: "{{ dict(keys|zip(values)) }}" 36 | # vars: 37 | # keys: "{{ ansible_play_hosts }}" 38 | # values: "{{ ansible_play_hosts| 39 | # map('extract', hostvars, ['mongo_arbiter']) | 40 | # list }}" 41 | # 42 | # - name: assert | create dictionary of arbiter system check 43 | # set_fact: 44 | # arb_system_check: "{{ dict(keys|zip(values)) }}" 45 | # vars: 46 | # keys: "{{ ansible_play_hosts }}" 47 | # values: "{{ ansible_play_hosts| 48 | # map('extract', hostvars, ['arb_check_stdout']) | 49 | # list }}" 50 | # 51 | # - name: assert | create list of arbiters 52 | # set_fact: 53 | # arbiter_system_check: "{{ arb_system_check | dict2items | 54 | # selectattr('value') | 55 | # map(attribute='key') | 56 | # list }}" 57 | # 58 | # - name: assert | set fact if there is an arbiter in the play 59 | # set_fact: 60 | # arbiter_present: true 61 | # when: arb_check.values() | list is any 62 | # 63 | # - name: assert | set fact if there is no arbiter in the play 64 | # set_fact: 65 | # arbiter_present: false 66 | # when: arb_check.values() | list is not any 67 | # 68 | # - name: assert | set fact if the cluster has an arbiter present 69 | # set_fact: 70 | # arbiter_system_present: true 71 | # when: arb_system_check.values() | list is any 72 | # 73 | # - name: assert | set fact if the cluster has no arbiter 74 | # set_fact: 75 | # arbiter_system_present: false 76 | # when: arb_system_check.values() | list is not any 77 | # 78 | # run_once: true 79 | # 80 | # - meta: end_play 81 | # - block: 82 | # 83 | # - name: scale | set fact for current hosts in cluster, without arbiter 84 | # set_fact: 85 | # current_cluster_hosts: "{{ check_cluster.stdout | 86 | # regex_replace(':[0-9]*','') }}" 87 | # when: inventory_hostname == run_on 88 | # 89 | # - name: scale | build current member list, without arbiter 90 | # set_fact: 91 | # current_members: >- 92 | # {{ 93 | # current_members | default([]) + 94 | # [{ 95 | # 'host': item + ':' + 96 | # mongo_port[hostvars[item].mongo_replication_role], 97 | # 'priority': member_weight[hostvars[item].mongo_replication_role] 98 | # }] 99 | # }} 100 | # loop: "{{ current_cluster_hosts }}" 101 | # vars: 102 | # mongo_port: 103 | # primary: "{{ mongo_net.port }}" 104 | # secondary: "{{ mongo_net.port }}" 105 | # member_weight: 106 | # primary: 3 107 | # secondary: 2 108 | # when: inventory_hostname == run_on 109 | # 110 | # - name: scale | reconfigure cluster with current hosts 111 | # community.mongodb.mongodb_replicaset: 112 | # login_host: localhost 113 | # login_port: "{{ mongo_net.port }}" 114 | # login_user: admin 115 | # login_password: "{{ mongo_admin_pass }}" 116 | # 117 | # replica_set: "{{ mongo_replication.replSetName }}" 118 | # reconfigure: true 119 | # force: true 120 | # members: "{{ current_members }}" 121 | # when: mongo_primary 122 | # 123 | # - name: scale | wait until cluster health is ok 124 | # community.mongodb.mongodb_status: 125 | # login_host: localhost 126 | # login_port: "{{ mongo_net.port }}" 127 | # login_user: admin 128 | # login_password: "{{ mongo_admin_pass }}" 129 | # 130 | # validate: minimal 131 | # poll: 5 132 | # interval: 12 133 | # replica_set: "{{ mongo_replication.replSetName }}" 134 | # when: mongo_primary 135 | # 136 | # when: 137 | # - arbiter_present 138 | # - arbiter_system_present 139 | # 140 | # # To speed up development proces, set this staticly 141 | # - name: scale | set fact for host list without arbiter 142 | # set_fact: 143 | # host_without_arb: 144 | # - test-multi-01 145 | # - test-multi-03 146 | # - test-multi-04 147 | # 148 | # - name: scale | build new member list to include new secondary 149 | # set_fact: 150 | # new_members: >- 151 | # {{ 152 | # new_members | default([]) + 153 | # [{ 154 | # 'host': item + ':' + 155 | # mongo_port[hostvars[item].mongo_replication_role], 156 | # 'priority': member_weight[hostvars[item].mongo_replication_role] 157 | # }] 158 | # }} 159 | # loop: "{{ host_without_arb }}" 160 | # when: inventory_hostname == run_on 161 | # vars: 162 | # mongo_port: 163 | # primary: "{{ mongo_net.port }}" 164 | # secondary: "{{ mongo_net.port }}" 165 | # member_weight: 166 | # primary: 3 167 | # secondary: 2 168 | # 169 | # - name: scale | reconfigure cluster to include the new secondary 170 | # community.mongodb.mongodb_replicaset: 171 | # login_host: localhost 172 | # login_port: "{{ mongo_net.port }}" 173 | # login_user: admin 174 | # login_password: "{{ mongo_admin_pass }}" 175 | # 176 | # replica_set: "{{ mongo_replication.replSetName }}" 177 | # reconfigure: true 178 | # members: "{{ new_members }}" 179 | # force: true 180 | # when: mongo_primary 181 | # 182 | # - name: scale | wait until cluster health is ok 183 | # community.mongodb.mongodb_status: 184 | # login_host: localhost 185 | # login_port: "{{ mongo_net.port }}" 186 | # login_user: admin 187 | # login_password: "{{ mongo_admin_pass }}" 188 | # 189 | # validate: default 190 | # poll: 5 191 | # interval: 12 192 | # replica_set: "{{ mongo_replication.replSetName }}" 193 | # when: mongo_primary 194 | # 195 | # - name: scale | block to inclue the arbiter if set 196 | # block: 197 | # 198 | # - name: scale | build member list including all hosts 199 | # set_fact: 200 | # members: >- 201 | # {{ 202 | # members | default([]) + 203 | # [{ 204 | # 'host': item + ':{{ mongo_net.port }}', 205 | # 'priority': member_weight[hostvars[item].mongo_replication_role] 206 | # }] 207 | # }} 208 | # loop: "{{ ansible_play_hosts }}" 209 | # run_once: true 210 | # vars: 211 | # member_weight: 212 | # primary: 3 213 | # secondary: 2 214 | # arbiter: 1 215 | # 216 | # - name: cluster | set fact for arbiter index number 217 | # set_fact: 218 | # arbiter_index: "{{ hostid }}" 219 | # when: hostvars[item].mongo_arbiter 220 | # loop: "{{ ansible_play_hosts }}" 221 | # loop_control: 222 | # index_var: hostid 223 | # 224 | # - name: scale | reconfigure cluster to include the arbiter 225 | # community.mongodb.mongodb_replicaset: 226 | # login_host: localhost 227 | # login_port: "{{ mongo_net.port }}" 228 | # login_user: admin 229 | # login_password: "{{ mongo_admin_pass }}" 230 | # 231 | # replica_set: "{{ mongo_replication.replSetName }}" 232 | # reconfigure: true 233 | # members: "{{ members }}" 234 | # when: mongo_primary 235 | # 236 | # - name: scale | wait until cluster health is ok 237 | # community.mongodb.mongodb_status: 238 | # validate: default 239 | # poll: 5 240 | # interval: 12 241 | # replica_set: "{{ mongo_replication.replSetName }}" 242 | # when: mongo_primary 243 | # 244 | # when: arbiter_present 245 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MongoDB 2 | 3 | An Ansible role that installs, configures and manages MongoDB for EL 8. 4 | A role for Ubuntu can be [found here](https://github.com/csuka/ansible_role_mongodb_ubuntu). 5 | 6 | **Please read this file carefully before deploying this Ansible role** 7 | 8 | ## Functionalities 9 | 10 | * Applies recommended production notes, e.g. [numa](https://docs.mongodb.com/manual/administration/production-notes/#configuring-numa-on-linux) and [disables transparent hugepages](https://docs.mongodb.com/manual/tutorial/transparent-huge-pages/) 11 | * Bootstrapping a cluster in a PSA architecture (primary, secondary, arbiter) 12 | * includes cluster verification 13 | * Secures connection by encrypting traffic via a keyfile, auto generated 14 | * Install either Community or the Enterprise edition 15 | * Easily to configure, with a future proof configuration method 16 | * Update playbook, supports patch releases 17 | * Add user defined users 18 | * Add user defined databases 19 | * Backup with mongodump 20 | * Logrotation, set from within mongo 21 | 22 | ## Requirements 23 | 24 | * Brain 25 | * On the controller node, ensure the [mongodb collection](https://docs.ansible.com/ansible/latest/collections/community/mongodb/index.html) is installed 26 | * The hosts are able to connect to each other, with preferably hostnames, and the set port, default 27017 27 | * Keep in mind there is enough disk space for data disk, and the backup if set 28 | 29 | ## Assertions 30 | 31 | There are several assertions to ensure a minimal valid configuration. Of course, it does not cover every use case, but most of them. 32 | Please follow this readme carefully. As a hint, for valid a configuration, see the variables files in the molecule folder. 33 | 34 | ## Versioning and edition 35 | 36 | The version and edition can be set. By default, the official mongodb repository and gpg key are added. 37 | 38 | ```yaml 39 | mongo_repo: true 40 | mongo_version: 5.0 41 | mongo_edition: org # or enterprise 42 | ``` 43 | 44 | ## Recommendations 45 | 46 | This section refers to this [official production notes of MongoDB](https://docs.mongodb.com/manual/administration/production-checklist-operations/#linux). 47 | 48 | This role includes several configuration recommendations, but not all. There is for example: "Turn off atime for the storage volume containing the database files." Such tasks are out of scope for this role. 49 | 50 | There are tasks which this role does apply if set, these are: 51 | 52 | * Start MongoDB with numactl, set in systemd file 53 | * Disabling zone reclaimm 54 | * Disabling transparent hugepages 55 | * Configure tuned profile 56 | 57 | See `tasks/thp.yml` and `tasks/numa.yml` for the actual changes to the system. 58 | 59 | These configuration recommendations are applied by default. 60 | 61 | ```yaml 62 | mongo_thp: true 63 | mongo_numa: true 64 | ``` 65 | 66 | ## Configuration variables 67 | 68 | First, see `defaults/main.yml`. 69 | 70 | The configuration file is placed at `/etc/mongod.conf`. 71 | 72 | The values set in the Ansible configuration are set **exactly** to the configuration file on the host. Only the keys are pre-defined. Example: 73 | 74 | ```yaml 75 | # Variable set in Ansible configuration 76 | mongo_operationprofiling: 77 | my_Value: 78 | anotherValue: something 79 | ``` 80 | 81 | Will result in the configuration file on disk: 82 | 83 | ```yaml 84 | operationProfiling: 85 | my_Value: 86 | anotherValue: something 87 | ``` 88 | 89 | If the key is set to an empty string, it will be commented out on the configuration file on disk. 90 | 91 | The possible keys to set are: 92 | ```yaml 93 | mongo_systemlog 94 | mongo_storage 95 | mongo_processmanagement 96 | mongo_security 97 | mongo_operationprofiling 98 | mongo_replication 99 | mongo_sharding 100 | mongo_auditlog 101 | mongo_snmp 102 | ``` 103 | 104 | There are pre-defined values, which are default for Mongo. 105 | If for some reason, it is desired to set custom key/values, use: 106 | 107 | ```yaml 108 | mongo_custom_cnf: 109 | my_key: 110 | my_value: true 111 | ``` 112 | 113 | ## Authorization 114 | 115 | By design there are 3 users created: `admin`, `backup` and `adminuser`. 116 | The admin has role root, the backup user has role backup and adminuser has role userAdminAnyDatabase. 117 | 118 | ```yaml 119 | mongo_admin_pass: 'change_me' 120 | mongo_adminuser_name: adminuser 121 | mongo_adminuser_pass: 'change_me' 122 | ``` 123 | 124 | ## Databases and users 125 | 126 | Taken from [the docs](https://docs.ansible.com/ansible/latest/collections/community/mongodb/mongodb_user_module.html), define your own set of users/databases. 127 | 128 | See the docs for [the possible roles](https://docs.mongodb.com/manual/reference/built-in-roles/). 129 | 130 | Users and databases are always configured via localhost, via user admin and database admin. 131 | When a cluster configured, configuring database and users is executed from the primary host. 132 | 133 | Set with: 134 | ```yaml 135 | mongo_user: 136 | # in it's most simple form 137 | - database: my_db 138 | name: my_user 139 | 140 | # standard values 141 | - database: another_db 142 | name: another_user 143 | update_password: on_create 144 | password: "123ABC!PASSWORD_XYZ" 145 | roles: 'readWrite,dbAdmin,userAdmin' 146 | state: present 147 | 148 | # all possible variables 149 | - database: my_db 150 | name: someone 151 | password: my_password 152 | update_password: on_create # default always 153 | roles: 'readWrite,dbAdmin,userAdmin' # default omitted 154 | state: absent # default present 155 | ssl: true # default omitted 156 | ssl_ca_certs: /path/to/ca_certs # default omitted 157 | ssl_cert_reqs: CERT_REQUIRED # default omitted 158 | ssl_certfile: /path/to/ssl_certfile # default omitted 159 | ssl_crlfile: /path/to/ssl_crlfile # default omitted 160 | ssl_keyfile: /path/to/ssl_keyfile # default omitted 161 | ssl_pem_passphrase: 'something' # default omitted 162 | auth_mechanism: PLAIN # default omitted 163 | connection_options: my_conn_options # default omitted 164 | create_for_localhost_exception: value # default omitted 165 | ``` 166 | 167 | To keep the role idempotent, you should set the value for `update_password` to `on_create`. Only when actually updating a password, set it to `always`, then switch back to `on_create`. 168 | 169 | 170 | ## Clustering 171 | 172 | When there are multiple hosts in the play, Ansible assumes clustering is configured. 173 | 174 | Clustering in a PSA (primary/secondary/arbiter) architecture is possible, or a primary/secondary/secondary setup. 175 | 176 | For security reasons, the connection between the hosts is secured with a keyfile. 177 | 178 | The [keyfile is automatically generated and deemed secure](https://docs.mongodb.com/manual/tutorial/enforce-keyfile-access-control-in-existing-replica-set/). 179 | 180 | ```yaml 181 | mongo_security: 182 | keyFile: /etc/keyfile_mongo 183 | ``` 184 | 185 | A 2 host cluster is a fundamentally broken design, as it cannot maintain uptime without a quorum and the ability of a node to go down to aid recovery. 186 | When there are exactly 2 hosts in the play, forming a cluster is not possible. 187 | Mongo will not cluster, because there must be a valid number of replicaset members. 188 | 189 | There are assertions in place to verify an uneven amount of hosts in the play. 190 | 191 | Configure with: 192 | ```yaml 193 | # set the role per host. in the host_vars 194 | mongo_replication_role: primary # or secondary, or arbiter 195 | 196 | # in group_vars/all.yml 197 | mongo_replication: 198 | replSetName: something 199 | ``` 200 | 201 | There can be only 1 primary and 1 arbiter set. 202 | 203 | You shouldn't change the design of the cluster once it has been deployed, e.g. change a secondary to an arbiter. 204 | 205 | Ensure to [disable read concern majority](https://docs.mongodb.com/v4.0/reference/read-concern-majority/#disable-read-concern-majority) when version 4.4 or lower is installed. 206 | 207 | ```yaml 208 | # not for version 5.0 or higher 209 | # and only when the architecture is PSA (Primary, Secondary, Arbiter) 210 | mongo_replication: 211 | replSetName: something 212 | enableMajorityReadConcern: false 213 | ``` 214 | 215 | ### Arbiter 216 | 217 | As per the [docs](https://docs.mongodb.com/manual/tutorial/add-replica-set-arbiter/#add-an-arbiter), avoid deploying more than one arbiter per replica set. 218 | 219 | Ansible will take care of adding the arbiter properly to the cluster. 220 | 221 | ```yaml 222 | mongo_replication_role: arbiter 223 | ``` 224 | 225 | ## Backup 226 | 227 | The back-up is configured to be set on either on a single host without replication, or on the first secondary host in the play. It is performed with [`mongodump`](https://docs.mongodb.com/manual/reference/program/mongodump/), set in cron. 228 | 229 | The backup scripts are **only** placed on the first applicable secondary node: 230 | 231 | ``` 232 | - host1 [primary] <-- backup scripts absent here 233 | - host2 [secondary] <-- backup scripts placed here 234 | - host3 [secondary] <-- backup scripts absent here 235 | ``` 236 | 237 | ```yaml 238 | mongo_backup: 239 | enabled: true 240 | dbs: 241 | - admin 242 | - config 243 | - local 244 | user: backup 245 | pass: change_me 246 | path: /var/lib/mongo_backups 247 | owner: mongod 248 | group: mongod 249 | mode: '0660' 250 | hour: 2 251 | minute: 5 252 | day: "*" 253 | retention: 46 # in hours 254 | ``` 255 | 256 | Ensure to change the password of the backup user, and allow the backup user to actually backup a given database. 257 | 258 | On disk, the result will be: 259 | ```bash 260 | [root@test-multi-03 mongo_backups]# pwd ; ls -larth 261 | /var/lib/mongo_backups 262 | total 4.0K 263 | drwxr-xr-x. 36 root root 4.0K Jan 20 12:33 .. 264 | lrwxrwxrwx 1 root root 46 Nov 20 12:37 latest -> /var/lib/mongo_backups/mongo_backup_2021-11-20 265 | drw-rw---- 3 mongod mongod 51 Nov 20 12:37 . 266 | drwxr-xr-x 5 root root 77 Nov 20 12:38 mongo_backup_2021-11-20 267 | ``` 268 | 269 | ## Logrotation 270 | 271 | Please [read the docs](https://docs.mongodb.com/manual/tutorial/rotate-log-files/). Ensure settings are configured properly. 272 | 273 | ## Updating 274 | 275 | Before updating, ensure proper testing is in place. Begin with reading the latest changes in the official docs. 276 | 277 | There is a separate update playbook, see `playbooks/update.yml`. Set the correct hostname in place and simply run the playbook. 278 | 279 | Updating can easily be done for patch versions, e.g. from 5.0.1 to 5.0.2. 280 | This role does not include major versioning upgrades due to breaking changes on each release and other obvious reasons. If this is desired, the logic is in place in this role to perform a major upgrade, you can easily built it yourself. 281 | 282 | New variables can be set when updating mongo. To update: 283 | 284 | ```yaml 285 | mongo_state: latest 286 | 287 | # setting new variables is possible when updating mongo 288 | mongo_net: 289 | new_variable: true 290 | ``` 291 | 292 | While updating, ensure applications don't write to mongo. Also, ensure a backup is created beforehand. 293 | 294 | ### Updating a replica set 295 | 296 | If a replication set is active, the cluster should be maintained after the update. As taken [from the docs](https://docs.mongodb.com/manual/tutorial/upgrade-revision/), the following steps are executed: 297 | 298 | ``` 299 | - verify cluster health, if ok, continue 300 | 301 | - shutdown mongo application on arbiter if present 302 | - update mongo on arbiter 303 | - place config on arbiter 304 | - start mongo on arbiter 305 | 306 | - wait until cluster health is ok 307 | 308 | - shutdown mongo application on a secondary 309 | - update mongo on secondary 310 | - place config on secondary 311 | - start mongo on secondary 312 | 313 | - wait until cluster health is ok 314 | 315 | - repeat for remaining secondaries 316 | 317 | - step down primary 318 | - update mongo on original primary 319 | - place config on original primary 320 | - start mongo on original primary 321 | 322 | - wait until cluster health is ok 323 | ``` 324 | 325 | ### Updating a sharded environment 326 | 327 | In development. 328 | 329 | ## Development 330 | 331 | * There is a reset playbook to remove all mongo files. This is useful for development purposes, see `tasks/reset.yml`. It is commented out by design 332 | 333 | ### Scaling 334 | 335 | Still in development... I am not even sure whenever I'll this functionality, since this is currently not even possible with mongo 5.0. 336 | It is not easy to configure scaling in mongo with Ansible, since the method is not straight forward. 337 | 338 | So far, I saw that the steps should be: 339 | - If arbiter is present in configuration and on system 340 | - remove arbiter from cluster 341 | - Add new secondary or secondaries 342 | - Add arbiter if configured 343 | 344 | I have tried configuring this countless amount of times, but always failed due to a system error. I decided to not include scaling for now. 345 | 346 | # Example playbook 347 | 348 | ```yaml 349 | - hosts: 350 | - host_mongo_primary 351 | - host_mongo_secondary 352 | - host_mongo_arbiter 353 | roles: 354 | - mongodb 355 | any_error_true: true 356 | vars: 357 | mongo_restart_config: true 358 | mongo_restart_seconds: 8 359 | mongo_thp: true 360 | mongo_numa: true 361 | mongo_replication: 362 | replSetName: replicaset1 363 | mongo_security: 364 | authorization: enabled 365 | keyFile: /etc/keyfile_mongo 366 | mongo_admin_pass: something 367 | mongo_adminuser_pass: something 368 | mongo_net: 369 | bindIp: 0.0.0.0 370 | port: 27017 371 | mongo_systemlog: 372 | destination: file 373 | logAppend: true 374 | path: /opt/somewhere/mongod.log 375 | mongo_storage: 376 | dbPath: /opt/mongo/ 377 | journal: 378 | enabled: true 379 | mongo_user: 380 | - database: burgers 381 | name: bob 382 | password: 12345 383 | state: present 384 | update_password: on_create 385 | pre_tasks: 386 | # ensure this is done 387 | # - name: ensure hosts can connect to each other via hostnames 388 | # template: 389 | # src: hosts.j2 390 | # dest: /etc/hosts 391 | ``` 392 | --------------------------------------------------------------------------------