Skip to content

Instantly share code, notes, and snippets.

@sivel
Created June 22, 2015 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sivel/60d741fe677e22518660 to your computer and use it in GitHub Desktop.
Save sivel/60d741fe677e22518660 to your computer and use it in GitHub Desktop.
Ansible inventory script that uses /etc/hosts as it's data source
#!/usr/bin/env python
# (c) 2015, Matt Martz <matt@sivel.net>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import sys
import json
import argparse
def etc_hosts():
try:
with open('/etc/hosts') as f:
hosts_text = f.read()
except Exception as e:
raise SystemExit(e)
hosts = {
'_meta': {
'hostvars': {}
}
}
for line in hosts_text.splitlines():
if not line.strip() or line.startswith('#'):
continue
names = line.split()
ip = names.pop(0)
for name in names:
if name not in hosts:
hosts[name] = {
'hosts': []
}
hosts[name]['hosts'].append(ip)
if ip in ['127.0.0.1', '::1'] or name == 'localhost':
hosts['_meta']['hostvars'][ip] = {
'ansible_connection': 'local',
'ansible_python_interpreter': sys.executable
}
else:
hosts['_meta']['hostvars'][ip] = {}
return json.dumps(hosts, indent=4, sort_keys=True)
def parse_args():
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--host', help='List details about a specific host')
group.add_argument('--list', action='store_true', default=False,
help='List active servers')
return parser.parse_args()
def main():
args = parse_args()
if args.host:
sys.stderr.write('--host is not implemented')
sys.stdout.write(etc_hosts())
sys.exit(0)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment