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:
- Red Hat Enterprise Linux 9.1 (with the BaseOS and Appstream repositories enabled)
- Ansible-core 2.13.3
- Python 3.9.14
[ 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_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD=password123 \
-p 27017:27017 \
mongo
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:
[defaults]
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:mongodb://root:password123@localhost:27017
[ 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
tasks:
- 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
test>
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
cache
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()
ansible>
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. ]
Sobre o autor
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.
Navegue por canal
Automação
Últimas novidades em automação de TI para empresas de tecnologia, equipes e ambientes
Inteligência artificial
Descubra as atualizações nas plataformas que proporcionam aos clientes executar suas cargas de trabalho de IA em qualquer ambiente
Nuvem híbrida aberta
Veja como construímos um futuro mais flexível com a nuvem híbrida
Segurança
Veja as últimas novidades sobre como reduzimos riscos em ambientes e tecnologias
Edge computing
Saiba quais são as atualizações nas plataformas que simplificam as operações na borda
Infraestrutura
Saiba o que há de mais recente na plataforma Linux empresarial líder mundial
Aplicações
Conheça nossas soluções desenvolvidas para ajudar você a superar os desafios mais complexos de aplicações
Programas originais
Veja as histórias divertidas de criadores e líderes em tecnologia empresarial
Produtos
- Red Hat Enterprise Linux
- Red Hat OpenShift
- Red Hat Ansible Automation Platform
- Red Hat Cloud Services
- Veja todos os produtos
Ferramentas
- Treinamento e certificação
- Minha conta
- Suporte ao cliente
- Recursos para desenvolvedores
- Encontre um parceiro
- Red Hat Ecosystem Catalog
- Calculadora de valor Red Hat
- Documentação
Experimente, compre, venda
Comunicação
- Contate o setor de vendas
- Fale com o Atendimento ao Cliente
- Contate o setor de treinamento
- Redes sociais
Sobre a Red Hat
A Red Hat é a líder mundial em soluções empresariais open source como Linux, nuvem, containers e Kubernetes. Fornecemos soluções robustas que facilitam o trabalho em diversas plataformas e ambientes, do datacenter principal até a borda da rede.
Selecione um idioma
Red Hat legal and privacy links
- Sobre a Red Hat
- Oportunidades de emprego
- Eventos
- Escritórios
- Fale com a Red Hat
- Blog da Red Hat
- Diversidade, equidade e inclusão
- Cool Stuff Store
- Red Hat Summit