Skip to main content

How to cache Ansible facts with MongoDB

Ansible's flexibility and variety of fact caching plugins allow you to design the solutions that best fit your requirements.
How to set SELinux to enforcing mode

Photo by Andrew Neel from Pexels

In How to cache Ansible facts with Redis, I demonstrated how to persist Ansible fact data using Redis. In this article, I will do something similar with MongoDB.

[ Related reading: An introduction to Ansible facts. ]

You can implement fact caching using MongoDB using the community.mongodb collection. This collection is not included in the default Ansible installation, but you may already have it installed. To check whether it is installed, run:

$ ansible-galaxy collection list

If the collection is not available, install it using ansible-galaxy:

$ ansible-galaxy collection install community.mongodb

Then list the installed cache plugins:

$ ansible-doc -t cache -l
community.mongodb.mongodb   Use MongoDB for caching

In addition to the requirements above, I used these software versions for this example:

[ Get started with IT automation with the Ansible Automation Platform beginner's guide. ]

Install MongoDB

To follow this example, you need MongoDB installed either locally on the control node or on a remote machine. For this example, I deployed MongoDB 6.0.4 locally using a container.

To run MongoDB as a container with Podman, use this command:

$ podman run \
    -d \
    --name mongo01 \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    -p 27017:27017 \

This command starts a MongoDB container, sets a username and password, and exposes it to the local TCP port 27017.

You can also refer to this GitHub repository for additional information.

Next, ensure the Python library pymongo>=3 is installed on the control node. Please note that version 4 of this library has issues with MongoDB version 6.0.4, so I used version 3.13.0 for this example.

$ pip install --user pymongo==3.13.0

Configure Ansible to cache facts using MongoDB

Update ansible.cfg to include:

fact_caching = community.mongodb.mongodb
fact_caching_timeout = 3600
fact_caching_connection = mongodb://root:password123@localhost:27017

The configuration values represent:

  • fact_caching: Indicates the cache plugin in use
  • fact_caching_timeout: Cache expiration timeout in seconds. For details consult How to cache Ansible facts with Redis.
  • fact_caching_connection: A connection string specifying details of how to connect to MongoDB. The format is mongodb://username:password@serverIP/hostname:port. For this example, use the values defined when you started the MongoDB container:

[ Write your first Ansible playbook in this hands-on interactive lab. ]

Test the fact cache

Run the setup module on target nodes to cache facts. You can wrap this command with the time command to determine how long it takes to gather facts:

$ time ansible localhost -m setup

Now you can use the playbook ansible_facts.yml with fact gathering disabled to test fact caching:

- name: Testing fact cache
  hosts: localhost
  gather_facts: false

    - debug: var=ansible_facts

Like before, you can also use the time command in addition to running the playbook to determine how long its takes to retrieve the cached facts:

$ time ansible-playbook ansible_facts.yml

This playbook should run faster than the setup command you ran before.

Ansible vs. Red Hat Ansible Automation Platform: Do you know the difference? ]

You can also check if the facts are cached correctly by logging into MongoDB and verifying that it created a database named ansible:

$ podman exec -it mongo01 mongosh mongodb://root:password123@localhost:27017
test> show dbs;
admin 100.00 KiB
ansible 68.00 KiB
config 72.00 KiB
local 72.00 KiB

You can then switch to the ansible database and verify that a collection called cache exists. Finally, run a query in this collection to find cached facts:

test> use ansible
switched to db ansible
ansible> show collections
ansible> db.cache.find()
    _id: 'ansible_factslocalhost',
    data: {
      ansible_fibre_channel_wwn: [],
      ansible_python: {
        version: {
          major: 3,
          minor: 9,
          micro: 14,
          releaselevel: 'final',
          serial: 0
        version_info: [ 3, 9, 14, 'final', 0 ],
        executable: '/usr/bin/python3',
        has_sslcontext: true,
        type: 'cpython'
      ansible_user_id: 'sysadmin',
      ansible_user_uid: 1000,
      ansible_user_gid: 1000,

... REDACTED ...

You can also bypass or clear the fact cache for every host in inventory by using the --flush-cache option when executing the playbook. This is important when the cache needs to be cleared before the timeout value expires. After executing the playbook with the option, the cache will be flushed and data cleared:

$ ansible-playbook -i inventory --flush-cache ansible_facts.yml
$ podman exec -it mongo01 mongosh mongodb://root:password123@localhost:27017
test> use ansible
switched to db ansible
ansible> db.cache.find()


Wrap up

You can use MongoDB to persist Ansible fact data across different executions. Ansible's flexibility and availability of different fact caching plugins allow you to design the solutions that best fit your requirements.

[ Download now: A system administrator's guide to IT automation. ]

Topics:   Ansible  
Author’s photo

Evans Amoany

I work as Unix/Linux Administrator with a passion for high availability systems and clusters. I am a student of performance and optimization of systems and DevOps. I have passion for anything IT related and most importantly automation, high availability, and security. More about me

Try Red Hat Enterprise Linux

Download it at no charge from the Red Hat Developer program.