How to set vars into ansible inventory?

2019-09-03 13:48发布

问题:

In playbook I'm using variable {{excluded_service}}. I want to run ansible playbook from python and provide this variable. And I can't use external inventory script to provide this variable. I am using to create inventory:

hosts = ["127.0.0.1"]
inventory=ansible.inventory.Inventory(hosts)

but I don't understand where I can add value of variable?

My code, that works with external inventory script:

import sys
import os
import stat
import json

import ansible.playbook
import ansible.constants as C
import ansible.utils.template
from ansible import errors
from ansible import callbacks
from ansible import utils
from ansible.color import ANSIBLE_COLOR, stringc
from ansible.callbacks import display

playbook="/opt/RDE/3p/ansible/loop/testloop.yml"
inventory="/opt/RDE/3p/ansible/loop/lxc.py"
connection="local"
timeout=10
subset=None

options={'subset': None, 'ask_pass': False, 'sudo': False, 'private_key_file': None, 'syntax': None, 'skip_tags': None, 'diff': False, 'check': False, 'remote_user': 'root', 'listtasks': None, 'inventory': '/opt/RDE/3p/ansible/loop/lxc.py', 'forks': 5, 'listhosts': None, 'start_at': None, 'tags': 'all', 'step': None, 'sudo_user': None, 'ask_sudo_pass': False, 'extra_vars': [], 'connection': 'smart', 'timeout': 10, 'module_path': None}
sshpass = None
sudopass = None
extra_vars = {}



def colorize(lead, num, color):
    """ Print 'lead' = 'num' in 'color' """
    if num != 0 and ANSIBLE_COLOR and color is not None:
        return "%s%s%-15s" % (stringc(lead, color), stringc("=", color), stringc(str(num), color))
    else:
        return "%s=%-4s" % (lead, str(num))

def hostcolor(host, stats, color=True):
    if ANSIBLE_COLOR and color:
        if stats['failures'] != 0 or stats['unreachable'] != 0:
            return "%-37s" % stringc(host, 'red')
        elif stats['changed'] != 0:
            return "%-37s" % stringc(host, 'yellow')
        else:
            return "%-37s" % stringc(host, 'green')
    return "%-26s" % host   


inventory = ansible.inventory.Inventory(options['inventory'])


hosts = ["127.0.0.1"]



#inventory=ansible.inventory.Inventory(hosts)

inventory.subset(options['subset'])
if len(inventory.list_hosts()) == 0:
    raise errors.AnsibleError("provided hosts list is empty")

inventory.set_playbook_basedir(os.path.dirname(playbook))
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
if options['step']:
    playbook_cb.step = options['step']
if options['start_at']:
    playbook_cb.start_at = options['start_at']



runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
pb = ansible.playbook.PlayBook(
            playbook=playbook,
            module_path=None,
            inventory=inventory,
            forks=options['forks'],
            remote_user=options['remote_user'],
            remote_pass=sshpass,
            callbacks=playbook_cb,
            runner_callbacks=runner_cb,
            stats=stats,
            timeout=options['timeout'],
            transport=options['connection'],
            sudo=options['sudo'],
            sudo_user=options['sudo_user'],
            extra_vars=extra_vars,

            private_key_file=options['private_key_file'],


            check=options['check'],
            diff=options['diff']        
        )

playnum = 0

failed_hosts = []
unreachable_hosts = []
try:
    print pb.run()

    hosts = sorted(pb.stats.processed.keys())
    print hosts
    display(callbacks.banner("PLAY RECAP"))
    playbook_cb.on_stats(pb.stats)

    for h in hosts:
        t = pb.stats.summarize(h)
        if t['failures'] > 0:
            failed_hosts.append(h)
        if t['unreachable'] > 0:
            unreachable_hosts.append(h)

    retries = failed_hosts + unreachable_hosts

    if len(retries) > 0:
        filename = pb.generate_retry_inventory(retries)
        if filename:
            display("           to retry, use: --limit @%s\n" % filename)

    for h in hosts:
        t = pb.stats.summarize(h)

        display("%s : %s %s %s %s" % (
            hostcolor(h, t),
            colorize('ok', t['ok'], 'green'),
            colorize('changed', t['changed'], 'yellow'),
            colorize('unreachable', t['unreachable'], 'red'),
            colorize('failed', t['failures'], 'red')),
            screen_only=True
        )

        display("%s : %s %s %s %s" % (
            hostcolor(h, t, False),
            colorize('ok', t['ok'], None),
            colorize('changed', t['changed'], None),
            colorize('unreachable', t['unreachable'], None),
            colorize('failed', t['failures'], None)),
            log_only=True
        )

except Exception as  e:
        print ("!!!!!!!ERROR: %s" % e)

回答1:

Specify the vars in a host_vars file? E.g. create a YAML file named /etc/ansible/host_vars/localhost with the vars you wanna put there.

I don't know, yet, how to specify it in Python code itself.

--- update ---

After a quick look the code, I don't think ansible supports specifying host variables when you specify hosts via host_list parameter. Hacks I can think of (if you must do this in python code) are:

  • [mis]use extra_vars parameter.
  • Write an inventory file (YAML or executable that just prints required JSON) from your python code and pass it's path as parameter inventory.

HTH