Query chef API server to know about available servers. Can be useful if most of your automation is done in chef but you wish to run some scripts via ansible. See the documentation on dynamic inventory for more details on the 'dynamic inventory' concept.
- Ansible [this script was tested with ansible 1.9.2]
- PyChef (
pip install PyChef
)
You need the following environment variables for the dynamic ansible inventory to work
export CHEF_USER=john
export CHEF_PEMFILE=/home/john/.chef/john.pem
export CHEF_SERVER_URL="https://my-chef-api"
(altenatively you can put the settings into a chef.ini file living in the same directory as the chef_inventory.py file)
You might find the information under ~/.chef/knife.rb
or ~/.chef/knife_local.rb
Copy chef_inventory.py to a location of your convenience, configuring your ansible.cfg
to include
hostfile=chef_inventory.py
or point to it when running your scripts with
ansible-playbook -i /path/to/chef_inventory.py
Make sure to make the file executable. (chmod +x chef_inventory.py
)
try it with
./chef_inventory.py --list
This python script chef_inventory.py
first queries the chef API to find servers, and caches the results in your home directory at ~/.ansible-chef.cache
.
That file is kept for 60 minutes (feel free to change self.cache_max_age = 3600
in the python code)
passing --list
then extracts server's IPs in the format ansible expects, e.g.
{
"my-webserver-group": [
"10.0.0.1",
"10.0.0.2"
],
"my-database-server-group": [
"10.0.0.3",
"10.0.0.4",
"10.0.0.5"
]
}
Within ansible playbooks or roles, you can then refer to hosts: my-webserver-group
, and name folders under group_vars
also my-webserver-group
, which will operate on those servers.
force cache refresh: ./chef_inventory.py --refresh-cache
Code based on https://gist.github.com/tjheeta/f3538c32965575e59bcd with some modifications to work with a recent version (1.9.2) of ansible and a custom chef setup, as well as to remove duplicate servers in the end result.