Operations 10 min read

Build an Ansible Custom Module to Backup MongoDB in Docker

An Ansible custom module was developed to back up MongoDB databases within a Docker container, including Dockerfile setup, Python handler code, parameter definitions, and a test playbook, with both successful and failure scenarios demonstrated, highlighting automation benefits for operations.

Efficient Ops
Efficient Ops
Efficient Ops
Build an Ansible Custom Module to Backup MongoDB in Docker

Background

Inspired by an article on using Ansible for MySQL backup, the author, who is not a dedicated operations engineer but frequently collaborates with ops teams, began exploring MongoDB backup automation. Since Ansible does not provide a built‑in module for this task, a custom solution was required.

Environment Preparation

A custom Docker image based on the official debian:latest image and the USTC mirror was built. The image installs Ansible, sshpass, pip, and the Python pymongo library, providing a ready‑to‑use environment for MongoDB maintenance.

FROM debian:latest
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list \
    && apt-get update -y \
    && apt-get upgrade -y \
    && apt-get install ansible -y \
    && apt-get install sshpass -y \
    && apt-get install pip -y \
    && apt-get autoclean
RUN pip3 install pymongo
RUN mkdir -p /etc/ansible/
CMD ["/bin/bash"]

The MongoDB database tools package mongodb-database-tools-debian10-x86_64-100.5.2 is downloaded and the mongodump binary is copied into the container:

docker cp mongodump ansible:/usr/bin/

Writing the mongodb_dump Custom Module

A Python module was created that builds a mongodump command and executes it via subprocess.run. The module returns success or fails with the error message.

def handler(module, state, login_host, login_user, login_password, name, target):
    cmd = "/usr/bin/mongodump -h %s -u %s -p %s -d %s -o %s -gzip" % (login_host, login_user, login_password, name, target)
    ret = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", timeout=3)
    if ret.returncode == 0:
        result = dict(result='success')
        module.exit_json(**result)
    else:
        module.fail_json(msg=ret.stderr)

Module parameters:

login_host (string): Host running the database.

login_user (string): Username for authentication.

login_password (string): Password for authentication.

name (string, aliases: db): Name of the database to dump.

state (string): Must be dump to trigger a backup.

target (string): Destination directory for the dump.

Playbook Orchestration and Testing

A simple playbook runs the custom module against a local MongoDB instance. Both a successful run and a failure caused by an incorrect password are shown.

---
- hosts: 127.0.0.1
  tasks:
    - name: "mongodb dump test"
      mongodb_dump:
        login_host: 192.168.1.100
        login_user: mongoadmin
        login_password: ******
        name: admin
        state: dump
        target: /tmp/mongo_{{ ansible_date_time.date }}

Successful execution output (truncated):

mongo.yml ******************************************************************
1 plays in mongo.yml

PLAY [127.0.0.1] ******************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [127.0.0.1]
META: ran handlers

TASK [mongodb dump test] ******************************************************************
ok: [127.0.0.1] => {"changed": false, "result": "success"}
META: ran handlers

PLAY RECAP ******************************************************************
127.0.0.1                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Failure output when the password is wrong:

fatal: [127.0.0.1]: FAILED! => {"changed": false, "msg": "2022-05-30T02:45:39.986+0000\tFailed: can't create session: could not connect to server: connection() error occured during connection handshake: auth error: unable to authenticate using mechanism \"SCRAM-SHA-256\": (AuthenticationFailed) Authentication failed.
"}
PLAY RECAP ******************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

Backup result screenshot:

Backup result
Backup result

Conclusion

The author successfully created, deployed, and tested an Ansible custom module for MongoDB backup, demonstrating the flexibility and extensibility of Ansible for operations automation. Further enhancements could include additional states, error handling, and integration with Ansible Tower or Galaxy.

Appendix: Native Ansible MongoDB Modules

mongodb_balancer module – Manages the MongoDB Sharded Cluster Balancer.

mongodb_index module – Creates or drops indexes on MongoDB collections.

mongodb_info module – Gather information about MongoDB instance.

mongodb_maintenance module – Enables or disables maintenance mode for a secondary member.

mongodb_monitoring module – Manages the free monitoring feature.

mongodb_oplog module – Resizes the MongoDB oplog.

mongodb_parameter module – Change an administrative parameter on a MongoDB server.

mongodb_replicaset module – Initialises a MongoDB replicaset.

mongodb_schema module – Manages MongoDB Document Schema Validators.

mongodb_shard module – Add or remove shards from a MongoDB Cluster.

mongodb_shard_tag module – Manage Shard Tags.

mongodb_shard_zone module – Manage Shard Zones.

mongodb_shell module – Run commands via the MongoDB shell.

mongodb_shutdown module – Cleans up all database resources and then terminates the mongod/mongos process.

mongodb_status module – Validates the status of the replicaset.

mongodb_stepdown module – Step down the MongoDB node from a PRIMARY state.

mongodb_user module – Adds or removes a user from a MongoDB database.

References

https://docs.ansible.com/ansible/latest/collections/community/mongodb/index.html

https://docs.ansible.com/ansible/latest/reference_appendices/module_utils.html

https://www.mongodb.com/try/download/database-tools

https://blog.csdn.net/weixin_37700260/article/details/106536612

《巧用Ansible实现MySQL备份》

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationBackupMongoDBAnsiblecustom module
Efficient Ops
Written by

Efficient Ops

This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.