Skip to content

Instantly share code, notes, and snippets.

@goldyfruit
Last active February 16, 2016 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldyfruit/1bab45a781af1988c96a to your computer and use it in GitHub Desktop.
Save goldyfruit/1bab45a781af1988c96a to your computer and use it in GitHub Desktop.
[ansible] Generate the /etc/hosts with Ansible
#!/usr/bin/env python
import json
data = {
"openstack": {
"children": [
"controller"
],
"vars": {
"envFile": "{{ inventory_dir }}/global.yml"
}
},
"controller": {
"hosts": [
"ctrl01.uoi.io",
"ctrl02.uoi.io",
"ctrl03.uoi.io"
],
"vars": {
"envFile": "{{ inventory_dir }}/global.yml"
}
},
"_meta": {
"hostvars": {
"ctrl01.uoi.io": {
"ansible_host": "10.0.0.60"
},
"ctrl02.uoi.io": {
"ansible_host": "10.0.0.61"
},
"ctrl03.uoi.io": {
"ansible_host": "10.0.0.62"
}
}
}
}
print json.dumps(data)
# {{ ansible_managed }}
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
{% for item in play_hosts %}
{% set short_name = item.split('.') %}
{{ hostvars[item]['ansible_host'] }} {{ item }} {{ short_name[0] }}
{% endfor %}
---
# tasks/hosts.yml
- name: Generate /etc/hosts file
template:
src=etc/hosts.j2
dest=/etc/hosts
@goldyfruit
Copy link
Author

Hi,

This how I generate my /etc/hosts file based on my dynamic inventory generated from a database.

Hope it helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment