Dynamic, Auditable, and Scalable IT Automation with Ansible, Python, and MongoDB
Introduction
Today's IT, network, and cloud teams are under continuous pressure to automate, audit, and scale their operations. Ansible—one of the world's leading automation tools—is favored for its agentless design, ease of adoption, and powerful orchestration capabilities. But for growing organizations and modern DevOps teams, combining Ansible with Python scripting and a flexible database like MongoDB can unlock an entirely new level of dynamic and auditable automation suited for the enterprise.
Why Ansible?
- Agentless: No need to install or manage software on target systems.
- Readable: Playbooks use YAML, making them simple to write, read, and share.
- Idempotent: Ensures infrastructure always matches your desired state—safe to run repeatedly.
- Highly extensible & cross-platform: Manage everything from Linux and Windows hosts to network devices and cloud APIs.
Power in Combining Ansible, Python, and MongoDB
When you bring these components together, you can:
- Manage Devices Dynamically: Store device information in MongoDB and build inventories on the fly using Python scripts—no more static config files.
- Centralize Audit Trails: Log all actions (changes, verifications, remediations) to a database, supporting compliance and quick troubleshooting.
- Scale with Ease: Expand infrastructure without re-working inventory files; all devices are queried in real time.
- Embed Custom Logic: Python can handle advanced logic, database calls, and interactions that exceed Ansible's core capabilities.
- Foster Team Collaboration: Centralized knowledge and clear audit histories mean faster onboarding and worry-free handoffs.
How It Works: Step-by-Step
🔹 Step 1: Dynamic Inventory from MongoDB (ms_device_inventory.py)
This Python script queries the MongoDB database in real time to fetch a list of Cisco IOS devices and generates a JSON inventory for Ansible.
import pymongo
import json
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client['network_db']
devices = db['ms_device'].find({"device_type": "cisco_ios"})
inventory = {"_meta": {"hostvars": {}}, "all": {"hosts": [], "vars": {}}}
for device in devices:
hostname = device["hostname"]
inventory["all"]["hosts"].append(hostname)
inventory["_meta"]["hostvars"][hostname] = {
"ansible_network_os": "cisco.ios.ios",
"ansible_connection": "network_cli",
"ansible_user": device.get("ansible_user", "admin"),
"ansible_password": device.get("ansible_password", ""),
"ansible_become": True,
"ansible_become_method": "enable",
"ansible_become_password": device.get("ansible_become_password", "")
}
print(json.dumps(inventory))
🔹 Step 2: Ansible Playbook for NTP Checking and Configuration (ntp_check_configure.yml)
This playbook connects to each host, checks its NTP configuration, adds the server if missing, and prepares an audit log.
- name: Check and configure NTP on Cisco devices
hosts: all
gather_facts: no
connection: network_cli
vars:
ntp_server: "192.168.1.1" # Set your NTP server
tasks:
- name: Check current NTP configuration
ansible.netcommon.cli_command:
command: "show running-config | include ntp server"
register: ntp_status
- name: Configure NTP if not configured
ansible.netcommon.cli_config:
lines:
- "ntp server {{ ntp_server }}"
when: ntp_status.stdout == ""
- name: Prepare audit log data
set_fact:
audit_log:
device: "{{ inventory_hostname }}"
ntp_configured: "{{ ntp_status.stdout == '' }}"
status: "{{ 'Configured NTP' if ntp_status.stdout == '' else 'NTP already configured' }}"
- name: Log action to MongoDB via Python script
delegate_to: localhost
run_once: true
vars:
audit_json: "{{ audit_log | to_json }}"
shell: echo '{{ audit_json }}' | ./log_to_mongo.py
🔹 Step 3: MongoDB Audit Logging with Python (log_to_mongo.py)
Captures every action and event, complete with timestamps.
import sys
import json
from pymongo import MongoClient
from datetime import datetime
data = json.load(sys.stdin)
client = MongoClient("mongodb://localhost:27017/")
db = client['network_db']
audit_col = db['ms_audit']
data['timestamp'] = datetime.utcnow()
result = audit_col.insert_one(data)
print(f"Inserted log with id: {result.inserted_id}")
Getting Started
Prerequisites:
- Python 3 and the
pymongopackage
pip install pymongo
- Ansible installed with the necessary network collections
- Access to a running MongoDB instance
- Device inventory initialized in the
ms_devicecollection
📌 Recommendation: Store all three scripts above in your repository. Use the inventory script as your Ansible dynamic inventory source, use the playbook for periodic configuration checks or pushes, and audit everything for compliance and troubleshooting.
Conclusion
For modern IT and DevOps teams, combining Ansible, Python, and MongoDB leads to dynamic, scalable, and fully auditable automation that works for small departments and global enterprises alike. It streamlines device management, boosts security and compliance, and lays the groundwork for collaborative, code-driven operations.
Try this workflow, extend it, and empower your team with true automation!
📋 Attachments
- 📎 Inventory script: ms_device_inventory.py
- 📎 Ansible playbook: ntp_check_configure.yml
- 📎 MongoDB audit logger: log_to_mongo.py
💡 Pro tip: For the best publishing experience on Medium or dev.to, copy this content as-is; both platforms auto-recognize code blocks, lists, and section headers for rich formatting.
Tags: #Ansible #Python #MongoDB #DevOps #Automation #NetworkAutomation #InfrastructureAsCode #ITAutomation