如何使用 Ansible 2.0 Python API 运行 Playbook? [英] How to use Ansible 2.0 Python API to run a Playbook?

查看:47
本文介绍了如何使用 Ansible 2.0 Python API 运行 Playbook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a python script which will call existing Ansible playbooks as it goes (because I want to loop over a list of plays while looping over a list of variables).

这篇文章很好地解释了它,对于 ansible pre-2.0:运行 ansible-playbook使用 Python API

This post explains it very well, for ansible pre-2.0: Running ansible-playbook using Python API

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

This doc explains it very well if you're writing a new playbook in your script: http://docs.ansible.com/ansible/developing_api.html

但我不知道如何使用 Python API 2.0 调用现有剧本,并且 ansible.runner 不再有效.

But I don't see how to call an existing playbook using Python API 2.0, and ansible.runner no longer works.

帮帮我,Stackoverflow-Wan Kenobi.你是我唯一的希望.

Help me, Stackoverflow-Wan Kenobi. You're my only hope.

推荐答案

文档非常缺乏,你必须开始这里

The documentation is surprisingly lacking and you'll have to get started here

话虽如此,这是我编写的一个快速脚本,可以运行剧本.

That being said, here is a quick script I hacked together that manages to run a playbook.

#!/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()

这篇关于如何使用 Ansible 2.0 Python API 运行 Playbook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆