#INSTALL.
YML
- name: Install required dependencies (gnupg and curl)
apt:
name:
- gnupg
- curl
state: present
update_cache: yes
- name: Remove existing MongoDB GPG key if present
file:
path: /usr/share/keyrings/mongodb-server-8.0.gpg
state: absent
- name: Add MongoDB GPG Key
shell: |
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -
o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
args:
executable: /bin/bash
- name: Add MongoDB 8.0 Repository
shell: |
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-
8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse"
> /etc/apt/sources.list.d/mongodb-org-8.0.list
- name: Update APT cache
apt:
update_cache: yes
- name: Install MongoDB
apt:
name: mongodb-org
state: present
#CONFIGURE.YML
- name: Copy MongoDB Config File
template:
src: mongod.conf.j2
dest: /etc/mongod.conf
notify: Restart MongoDB
- name: Restart MongoDB
service:
name: mongod
state: restarted
enabled: yes
- name: Create Keyfile for Authentication
copy:
content: "{{ lookup('password', '/dev/null length=32
chars=ascii_letters,digits') }}"
dest: /etc/mongo-keyfile
owner: mongodb
group: mongodb
mode: '0600'
- name: Set MongoDB to Start on Boot
systemd:
name: mongod
enabled: yes
state: started
#MAIN.YML
- import_tasks: install.yml
- import_tasks: configure.yml
- import_tasks: start.yml
- import_tasks: replica_init.yml
#REPLICA_INIT.YML
- name: Copy Replica Set Initialization Script
template:
src: replica_init.js.j2
dest: /root/replica_init.js
- name: Initialize MongoDB Replica Set
command: mongosh /root/replica_init.js
when: inventory_hostname == "mongo-master"
#START.YML
- name: Start MongoDB Service
systemd:
name: mongod
state: started
enabled: yes
#/templates/mongod.conf.j2
storage:
dbPath: /var/lib/mongodb
net:
bindIp: 0.0.0.0
port: 27017
replication:
replSetName: rs0
#templates/replica_init.js.j2
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "192.168.1.59:27017" },
{ _id: 1, host: "192.168.1.37:27017" }
]
});