尝试在python中为ansible创建动态主机文件

尝试在python中为ansible创建动态主机文件,python,ubuntu,vagrant,Python,Ubuntu,Vagrant,这是我在这里的第一篇帖子,所以如果有任何问题或者有什么不愉快的事情,请不要犹豫 我正在尝试使用一个动态主机文件,这样我就可以构建多个流浪机器,而不必首先管理主机文件。这是我在网上发现的: #!/usr/bin/env python # Adapted from Mark Mandel's implementation # https://github.com/ansible/ansible/blob/devel/plugins/inventory/vagrant.py import ar

这是我在这里的第一篇帖子,所以如果有任何问题或者有什么不愉快的事情,请不要犹豫

我正在尝试使用一个动态主机文件,这样我就可以构建多个流浪机器,而不必首先管理主机文件。这是我在网上发现的:

    #!/usr/bin/env python
# Adapted from Mark Mandel's implementation
# https://github.com/ansible/ansible/blob/devel/plugins/inventory/vagrant.py
import argparse
import json
import paramiko
import subprocess
import sys


def parse_args():
    parser = argparse.ArgumentParser(description="Vagrant inventory script")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--list', action='store_true')
    group.add_argument('--host')
    return parser.parse_args()


def list_running_hosts():
    cmd = "vagrant status --machine-readable"
    status = subprocess.check_output(cmd.split()).rstrip()
    hosts = []
    for line in status.split('\n'):
        (_, host, key, value) = line.split(',')
        if key == 'state' and value == 'running':
            hosts.append(host)
    return hosts


def get_host_details(host):
    cmd = "vagrant ssh-config {}".format(host)
    p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    config = paramiko.SSHConfig()
    config.parse(p.stdout)
    c = config.lookup(host)
    return {'ansible_ssh_host': c['hostname'],
            'ansible_ssh_port': c['port'],
            'ansible_ssh_user': c['user'],
            'ansible_ssh_private_key_file': c['identityfile'][0]}


def main():
    args = parse_args()
    if args.list:
        hosts = list_running_hosts()
        json.dump({'vagrant': hosts}, sys.stdout)
    else:
        details = get_host_details(args.host)
        json.dump(details, sys.stdout)

if __name__ == '__main__':
    main()
但是,当我运行此命令时,会出现以下错误:

ERROR! The file inventory/vagrant.py is marked as executable, but failed to execute correctly. If this is not supposed to be an executable script, correct this with `chmod -x inventory/vagrant.py`.
ERROR! Inventory script (inventory/vagrant.py) had an execution error: Traceback (most recent call last):
  File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 52, in <module>
    main()
  File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 45, in main
    hosts = list_running_hosts()
  File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 24, in list_running_hosts
    (_, host, key, value) = line.split(',')
ValueError: too many values to unpack

ERROR! inventory/vagrant.py:4: Expected key=value host variable assignment, got: argparse
错误!文件inventory/vagrant.py被标记为可执行文件,但未能正确执行。如果这不是一个可执行脚本,请使用“chmod-x inventory/vagrant.py”更正。
错误!清单脚本(Inventory/vagrant.py)有一个执行错误:回溯(最近一次调用last):
文件“/home/sebas/Desktop/playbooks/inventory/vagrant.py”,第52行,在
main()
文件“/home/sebas/Desktop/playbooks/inventory/vagrant.py”,主文件第45行
hosts=列出运行的主机
文件“/home/sebas/Desktop/playbooks/inventory/vagrant.py”,第24行,在运行主机列表中
(_,主机,键,值)=line.split(','))
ValueError:要解压缩的值太多
错误!inventory/vagrant.py:4:Expected key=value主机变量赋值,get:argparse

有人知道我做错了什么吗?提前谢谢你们

我猜问题在于
vagrant status
命令将仅在包含vagrant文件的目录中工作,或者如果指定了目标机器的ID

要获取系统上所有活动漫游环境的状态,应改用
Vagrant global status
。但是全局状态有一个缺点:它使用缓存,并且不主动验证机器的状态


因此,为了可靠地确定状态,首先我们需要获取所有具有
vagrant全局状态的虚拟机的ID
,然后使用
vagrant status ID

检查这些ID。您是否检查了这些ID是否无效:\now I get File”/home/sebas/Desktop/playbooks/inventory/vagrant.py“,第21行,在列表“运行”中,hosts status=subprocess.check\u output(cmd.split(“,”).rstrip()文件“/usr/lib/python2.7/subprocess.py”,第567行,在check\u output process=Popen(stdout=PIPE,*popenargs,**kwargs)文件“/usr/lib/python2.7/subprocess.py”,第711行,init errread,errwrite)文件“/usr/lib/python2.7/subprocess.py”,第1340行,在_execute_child raise child_exception OSError:[Errno 2]中没有这样的文件或目录oops,我最初的假设是完全错误的。编辑了答案。