如何使用 Ansible 2.0 Python API 运行 Playbook?

问题描述 投票:0回答:1

我正在尝试编写一个 python 脚本,它将在运行时调用现有的 Ansible 剧本(因为我想在循环变量列表的同时循环播放列表)。

这篇文章对 ansible 2.0 之前的版本解释得很好:使用 Python API 运行 ansible-playbook

如果您在脚本中编写新的剧本,该文档会很好地解释它:http://docs.ansible.com/ansible/developing_api.html

但我不知道如何使用 Python API 2.0 调用现有的 playbook,并且 ansible.runner 不再工作。

python api ansible ansible-2.x
1个回答
18
投票

文档出人意料地缺乏,你必须从这里开始

话虽这么说,这是我编写的一个快速脚本,可以成功运行剧本。

#!/usr/bin/env python

import os
import sys
from collections import namedtuple

from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_executor import PlaybookExecutor

variable_manager = VariableManager()
loader = DataLoader()

inventory = Inventory(loader=loader, variable_manager=variable_manager,  host_list='/home/slotlocker/hosts2')
playbook_path = '/home/slotlocker/ls.yml'

if not os.path.exists(playbook_path):
    print '[INFO] The playbook does not exist'
    sys.exit()

Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', 'connection','module_path', 'forks', 'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])
options = Options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='slotlocker', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method=None, become_user='root', verbosity=None, check=False)

variable_manager.extra_vars = {'hosts': 'mywebserver'} # This can accomodate various other command line arguments.`

passwords = {}

pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)

results = pbex.run()
© www.soinside.com 2019 - 2024. All rights reserved.