How to prompt user to enter a hostname which then gathers it from a large list

473 Views Asked by At

Using python through ansible I gathered a list of 7000 hostnames from DNS, but I want to prompt the user to enter a hostname and in return, the hostname will appear if present.

But it should be optional whether to look at the whole list or just one specified hostname.

The script is executed in xshell 5.

Any idea how I can proceed?

2

There are 2 best solutions below

0
On

One way you could do this would be using input(python3) (or raw_input(python2)) or specifying hostname as an argument to your script. You could get output from all by not specifying any hostname.

Assuming your hostnames are in a python list dnshostnames:

input:

hostname = input("specify hostname (blank for all)").strip()
if hostname:
    if hostname in dnshostnames:
        print("{} in host name list".format(hostname))
else:
    print("Hostnames:\n\n","\n".join(dnshostnames)

or as argument to script:

import sys

if len(sys.argv<1): 
    #assuming hostname has no whitespace in name
    if sys.argv[1] in dnshostnames:
        print("{} in host name list".format(hostname))
else:
    print("Hostnames:\n\n","\n".join(dnshostnames)

which would then be called as python myscript.py myhostname

0
On

Using python through ansible

I assume this means you use a dynamic inventory script. The not satisfying but common approach seen in most inventory scripts is to use environment variables affect the behavior of inventory scripts, since currently it is not possible to access any parameter passed to ansible.

So, if you call ansible like this:

LIMIT_PATTERN="some-host[0-9]*" ansible-playbook -i your-script.py

You could access the pattern as os.environ.get('LIMIT_PATTERN') and use it to limit your result set.

It's not advisable to shove all 7000 hosts to Ansible and later limit the result in ansible for example with a vars_prompt or the pause module, since it slows Ansible startup considerably down.