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. ]
저자 소개
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.
채널별 검색
오토메이션
기술, 팀, 인프라를 위한 IT 자동화 최신 동향
인공지능
고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트
오픈 하이브리드 클라우드
하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요
보안
환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보
엣지 컴퓨팅
엣지에서의 운영을 단순화하는 플랫폼 업데이트
인프라
세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보
애플리케이션
복잡한 애플리케이션에 대한 솔루션 더 보기
오리지널 쇼
엔터프라이즈 기술 분야의 제작자와 리더가 전하는 흥미로운 스토리
제품
- Red Hat Enterprise Linux
- Red Hat OpenShift Enterprise
- Red Hat Ansible Automation Platform
- 클라우드 서비스
- 모든 제품 보기
툴
체험, 구매 & 영업
커뮤니케이션
Red Hat 소개
Red Hat은 Linux, 클라우드, 컨테이너, 쿠버네티스 등을 포함한 글로벌 엔터프라이즈 오픈소스 솔루션 공급업체입니다. Red Hat은 코어 데이터센터에서 네트워크 엣지에 이르기까지 다양한 플랫폼과 환경에서 기업의 업무 편의성을 높여 주는 강화된 기능의 솔루션을 제공합니다.