Tuesday, August 1, 2023

Building Dynamic inventory in Ansible

 Hello Guys,

I have recently worked on a project which involved fetching a data from multiple server at the run time and manipulating it and displaying it Grafana dashboard. the most interesting part of it was generating the  inventory at runtime and using it in the same playbook

let us say we have a mysql db with table contain the information of all the servers 


currently showing 3 column which are of our interest  hostname,ip and some var value

building the dynamic inventory the playbook look like below

---
- hosts: localhost
connection: local
tasks:

- set_fact:
db_database: inventorydb
db_host: inventorydbhost
- name: Query Datacenter hosts from DB
mysql_query:
login_host: "{{ db_host }}"
login_db: "{{ db_database }}"
login_user: "{{ db_user }}"
login_password: "{{ db_password }}"
query:
- select distinct(hostname) from inventory ;
single_transaction: yes
register: dc_db_query


- name: Generate hosts file
template:
src: ./templates/hosts.j2
dest: hosts

- meta: refresh_inventory

 The host.j2 file present in the templates look like this

[all]
{% for item in dc_db_query.query_result[0] %}
{{ item.hostname }}
{% endfor %}

This will build the inventory at the run time as well as  the meta flag at the bottom will help us to refresh the inventory to use it on all the host which it will return 

let me know if you want to know on any other topics