Skip to content

Commit

Permalink
Create mongo-key for replication (#1)
Browse files Browse the repository at this point in the history
The system will create a mongo-key file in /etc/ssl when you enable replication and authentication in mongo.
  • Loading branch information
Madias2222 authored Jan 14, 2025
1 parent e774cd1 commit ecaf5ee
Showing 1 changed file with 40 additions and 9 deletions.
49 changes: 40 additions & 9 deletions roles/mongodb_auth/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,6 @@
# When authorization is enabled in mongo using a replica set, the members of
# the set will be required to authenticate too. This is accomplished with a
# keyFile or x509 certificate. It is assumed that this keyFile already exists.
- name: Upload the key file if this is a replica set
ansible.builtin.copy:
src: "{{ mongo_auth_keyfile_source }}"
dest: "{{ mongo_auth_keyfile_destination }}"
mode: '0400'
group: "{{ mongo_group }}"
owner: "{{ mongo_owner }}"
when: mongodb_replication | bool

- name: Modify mongod.conf to enable authorization
ansible.builtin.lineinfile:
path: "{{ mongo_conf_file }}"
Expand All @@ -27,6 +18,46 @@
line: " keyFile: {{ mongo_auth_keyfile_destination }}"
when: mongodb_replication | bool

- name: Check if key exists on the first node
when:
- inventory_hostname == groups['mongodb'][0]
- mongodb_replication | bool
run_once: true
ansible.builtin.stat:
path: "{{ mongo_auth_keyfile_destination }}"
register: keyfile_stat

- name: Generate key (if missing) and copy to all nodes
when:
- inventory_hostname == groups['mongodb'][0]
- mongodb_replication | bool
- not keyfile_stat.stat.exists
run_once: true
block:
- name: Generate a new replica set key with OpenSSL
ansible.builtin.shell:
cmd: openssl rand -base64 756 > "{{ mongo_auth_keyfile_destination }}"
args:
creates: "{{ mongo_auth_keyfile_destination }}"

- name: Set key file ownership and permissions
ansible.builtin.file:
path: "{{ mongo_auth_keyfile_destination }}"
owner: "{{ mongo_owner }}"
group: "{{ mongo_group }}"
mode: '0400'

- name: Copy the generated key to all MongoDB nodes
ansible.builtin.copy:
src: "{{ mongo_auth_keyfile_destination }}"
dest: "{{ mongo_auth_keyfile_destination }}"
remote_src: true
owner: "{{ mongo_owner }}"
group: "{{ mongo_group }}"
mode: '0400'
loop: "{{ groups['mongodb'] }}"
delegate_to: "{{ item }}"

- name: Check the auth status
ansible.builtin.include_role:
name: mongodb_common
Expand Down

0 comments on commit ecaf5ee

Please sign in to comment.