In [ ]:
cd /notebooks/exercise-05
In [ ]:
!cat inventory
The ansible
executable can process inventory files
In [ ]:
!ansible -i inventory --list-host all
In [ ]:
# Use this cell for the exercise
In [ ]:
# The ping module is very useful.
# Use it whenever you want to check connectivity!
!ansible -m ping -i inventory web_rome
In [ ]:
#To create custom inventory scripts just use python ;) and set it in
!grep inventory ansible.cfg # inventory = ./docker-inventory.py
In [ ]:
"""List our containers.
Note: this only works with docker-compose containers.
"""
from __future__ import print_function
#
# Manage different docker libraries
#
try:
from docker import Client
except ImportError:
from docker import APIClient as Client
c = Client(base_url="http://172.17.0.1:2375")
# Define a function to make it clear!
container_fmt = lambda x: (
x['Names'][0][1:],
x['Labels']['com.docker.compose.service'],
x['NetworkSettings']['Networks']['bridge']['IPAddress'],
)
for x in c.containers():
try:
print(*container_fmt(x), sep='\t\t')
except KeyError:
# skip non-docker-compose containers
pass
In [ ]:
# Ansible accepts
import json
inventories = {
'web': {
'hosts': ['ws-1', 'ws-2'],
},
'db': {
'hosts': ['db-1', 'db-2'],
}
}
# like this
print(json.dumps(inventories, indent=1))
In [ ]:
# You can pass variables to generated inventories too
inventories['web']['host_vars'] = {
'ansible_ssh_common_args': ' -o GSSApiAuthentication=no'
}
print(json.dumps(inventories, indent=1))
Reuse the code in inventory-docker.py to print a json inventory that:
Test it in the cell below.
NOTE: there's a docker inventory script shipped with ansible
In [ ]:
!ansible -m ping -i inventory-docker-solution.py all
Modify the inventory-docker.py to skip StrictHostKeyChecking only on web hosts.
In [ ]:
# Test here your inventory
In [ ]:
# Use this cell to test the exercise
In [ ]:
!tree group_vars
If you have different inventories, you can store different set of variable in custom files.
The all
ones will be shared between all inventories
In [ ]:
# Test here the new inventory file
Inventory variables can store almost everything and even describe the architecture of your deployment
In [ ]:
!cat group_vars/example
We can even mix and mojo group_vars
and inventory
, as we'll see in the next lessons.