Skip to content

Instantly share code, notes, and snippets.

@hvanderlaan
Last active July 20, 2021 03:32
Show Gist options
  • Save hvanderlaan/95eaf4b00408dfba8a9975f99890a4f0 to your computer and use it in GitHub Desktop.
Save hvanderlaan/95eaf4b00408dfba8a9975f99890a4f0 to your computer and use it in GitHub Desktop.
ansible dynamic inventory script for local network
#!/usr/bin/env python
"""
dynamic-inv-local-network.py - dynamic ansible inventory file for use a local network
usage: ansible --ask-vault-password -i dynamic-inv-local-network.py all -m ping
"""
from __future__ import (print_function, absolute_import, division, unicode_literals)
import socket
import subprocess
# json is not alway default installed, if json is not installed simplejson is installed
# for this reason python will check is json is installed or it will fallback to simplejson
try:
import json
except ImportError:
import simplejson as json
def inventory():
""" function: create a dynamicly generated inventory for ansible """
ipaddrs = find_nodes()
return {
'all': {
'hosts': [ipaddrs],
'vars': {},
},
'_meta': {
'hostvars': {
ipaddrs: {
'ansible_ssh_user': 'ansible',
}
},
},
'nodes': [ipaddrs]
}
def find_nodes():
""" function: return ipaddress in you local network where port 22 is open """
for ip in all_local_ipaddrs():
if port_22_is_open(ip):
return ip
def all_local_ipaddrs():
""" function: find all active ipaddress in your local network """
lines = subprocess.check_output(['arp', '-a']).split('\n')
for line in lines:
if '(' not in line:
continue
afterbracketopen = line.split('(')[1]
ipaddr = afterbracketopen.split(')')[0]
yield ipaddr
def port_22_is_open(ipaddr):
""" function: check if port 22 is open """
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ipaddr, 22))
sock.close()
return result == 0
def main():
""" function: main function for returning the dynamic inventory """
print('{}' .format(json.dumps(inventory(), sort_keys=True, indent=2)))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment