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

问题描述

我想写一个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-剧本

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

本文档介绍非常好,如果你正在写在脚本中一个新的剧本:

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.

帮助我,#1比旺。你是我唯一的希望。

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 API的Python运行剧本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:22