Ansible - Define Inventory at run time

后端 未结 2 1932
灰色年华
灰色年华 2021-02-10 09:06

I am liitle new to ansible so bear with me if my questions are a bit basic.

Scenario:

I have a few group of Remote hosts such as [EPCs] [Clients] and [Testers] I

2条回答
  •  醉话见心
    2021-02-10 09:14

    I don't think you can define an inventory at run time. One thing you can do is, write a wrapper script over Ansible which will first prompt user for the hosts and then dynamically structure an ansible-playbook command.

    I would prefer doing this using python, but you can use any language of your choice.

    $ cat ansible_wrapper.py 
    import ConfigParser
    import os
    
    nodes = ''
    inv = {}
    
    hosts =  raw_input("Enter hosts: ")
    hosts = hosts.split(",")
    
    config = ConfigParser.ConfigParser(allow_no_value=True)
    config.readfp(open('hosts'))
    sections = config.sections()
    
    for i in range(len(sections)):
        inv[sections[i]] = hosts[i]
    
    
    for key, value in inv.items():
        for i in range(int(value)):
            nodes = nodes + config.items(key)[i][0] + ";"
    
    
    command = 'ansible-playbook -i hosts myplaybook.yml -e "nodes=%s"' % (nodes)
    print "Running command: ", command
    os.system(command)
    

    Note: I've tried running this script only using python2.7

提交回复
热议问题