如何将vars设置为ansible inventory?

How to set vars into ansible inventory?

在剧本中,我使用变量 {{excluded_service}}。我想 运行 来自 python 的 ansible 剧本并提供此变量。而且我不能使用外部清单脚本来提供这个变量。 我正在使用创建库存:

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

但我不明白在哪里可以添加变量的值?

我的代码,适用于外部清单脚本:

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)

host_vars file 中指定变量? 例如。用你想放在那里的变量创建一个名为 /etc/ansible/host_vars/localhost 的 YAML 文件。

我还不知道如何在 Python 代码本身中指定它。

---更新---

快速查看代码后,我认为当您通过 host_list 参数指定主机时,ansible 不支持指定主机变量。我能想到的技巧(如果你必须在 python 代码中这样做)是:

  • [错误]使用 extra_vars 参数。
  • 从您的 python 代码中编写清单文件(YAML 或仅打印所需 JSON 的可执行文件)并将其路径作为参数传递 inventory

HTH