How to use external variable inside an ansible inventory file.

63 views
Skip to first unread message

anoop....@tarams.com

unread,
Dec 15, 2015, 2:30:25 AM12/15/15
to Ansible Project
Hi,

I have an inventory file 'inventory/localhost' and contains;
[localhost]
"{{MYSITE_NAME}}-local.com"    ansible_ssh_port=2222


Lets say 'MYSITE_NAME' is a variable defined in some file. I need to access this inside my inventory file. Please suggest some solution.

anoop....@tarams.com

unread,
Dec 16, 2015, 2:10:16 AM12/16/15
to Ansible Project
Any suggestion guys??

pixel fairy

unread,
Dec 26, 2015, 7:43:58 PM12/26/15
to Ansible Project
theres probably an easier way, but since your setting up for a dynamic inventory, you might as well use it.

http://docs.ansible.com/ansible/developing_inventory.html

heres an example in python for lxc containers.

#!/usr/bin/env python

import yaml
import json

with open('containers.yml') as fp:
    c
= yaml.load(fp)
containers
= c['containers']

inventory
= {
   
'containers': { 'hosts': [] },
   
'_meta': { 'hostvars': {} }
}

for k, v in containers.items():
    inventory
['containers']['hosts'].append(k)
   
if 'groups' in v:
       
for group in v['groups']:
           
if group not in inventory:
                inventory
[group] = { 'hosts':[] }
            inventory
[group]['hosts'].append(k)
    inventory
['_meta']['hostvars'][k] = {}
    inventory
['_meta']['hostvars'][k]['ansible_ssh_host'] = v['address']

print(json.dumps(inventory,indent=2))


and the containers,

containers:
  vpn
:
    address
: 192.168.114.4
    forwards
:
   
- { transport: udp, host: 1194, container: 1194 }
  reverseproxy
:
    address
: 192.168.114.10
    forwards
:
   
- { transport: tcp, host: 80, container: 80 }
   
- { transport: tcp, host: 443, container: 443 }
  web1
:
    hostname
: web1.example.lan
    address
: 192.168.114.11
    cnames
:
   
- moreweb.example.lan
   
- another.example.lan
    groups
:
     
- web
  web2
:
    hostname
: web2.example.lan
    address
: 192.168.114.12
    groups
:
     
- web


Reply all
Reply to author
Forward
0 new messages