Nagri
Nagri

Reputation: 3136

Directory structure for huge ansible inventory file

Our ansible inventory file is getting bigger and bigger day by day. so we wanted to modularize it with directories and file. say for example.

[webservers]
foo.example.com
bar.example.com

[dbservers]
one.example.com
two.example.com
three.example.com

this can be converted into

|--production
|  |--WEBSERVERS
|  |  |--webservers
|  |--DBSERVERS
|  |  |--dbservers

Where webservers is a file;

[webservers]
foo.example.com
bar.example.com

and dbservers is a file;

[dbservers]
one.example.com
two.example.com
three.example.com

for simple inventory file it works fine. Problem comes when I create group of groups.

like

[webservers]
foo.example.com
bar.example.com

[dbservers]
one.example.com
two.example.com
three.example.com

[master:children]
webservers
dbservers

I cant imagine a directory structure for this and it. Can someone please guide me to the right tutorial. Thanks

Upvotes: 0

Views: 2569

Answers (1)

Vor
Vor

Reputation: 35109

Ansible supports "dynamic inventories" you can read more about this in here: http://docs.ansible.com/ansible/developing_inventory.html

What is it:

Simple script (python, ruby, shell etc) that produces JSON in a specific format.

How can I benefit from it:

Create a folder structure that best reflects your needs, and place your servers config in there. Then create a simple executable file to read those files and output a result.

Example:

inventory.py:

#!/usr/bin/python

import yaml
import json

web = yaml.load(open('web.yml', 'r'))

inventory = { '_meta': { 'hostvars': {} } }

# Individual server configuration
for server, properties in web['servers'].iteritems():
  inventory['_meta']['hostvars'][server] = {}
  inventory['_meta']['hostvars'][server]['ansible_ssh_host'] = properties['ip']

# Magic group for all servers
inventory['all'] = {}
inventory['all']['hosts'] = web['servers'].keys()

# Groups of servers
if 'groups' in web:
  for group, properties in web['groups'].iteritems():
    inventory[group] = {}
    inventory[group]['hosts'] = web['groups'][group]

print json.dumps(inventory, indent=2)
web.yml
---
servers:
  foo:
    ip: 192.168.42.10
  bar:
    ip: 192.168.42.20

groups:
  webservers:
  - foo
  dbservers:
  - bar

Then call your playbook as usuall and you will get the same result as if you would use standart ini file.

Upvotes: 7

Related Questions