以编程方式运行 Ansible playbook? [英] Run Ansible playbook programmatically?

查看:24
本文介绍了以编程方式运行 Ansible playbook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 应用程序,它调用下面的代码,计划通过 Ansible API 以编程方式运行 Ansible playbook,而不是使用类似子进程的东西.

I have a python application that calls the code below with the plan to run an Ansible playbook programmatically via the Ansible API versus using something like subprocess.

下面的代码运行但实际上似乎没有执行.获取结果的输出只会给我一个看起来像的字典:

The code below runs but nothing actually seems to get executed. Grabbing the output of results just gives me a dictionary that looks like:

[{'plays': [localhost], 'playbook': 'playbooks/asg_elb_example.yml'}]

我不确定我哪里出错了或我遗漏了什么.这是我正在运行的代码.

I am not sure where I am going wrong or what I am missing. Here is the code I am running.

import os
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(SCRIPT_DIR)

import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.playbook_executor import PlaybookExecutor

def ansible_part():
    playbook_path = "playbooks/asg_elb_example.yml"
    inventory_path = "hosts"

    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff', 'listhosts', 'listtasks', 'listtags', 'syntax'])
    loader = DataLoader()
    options = Options(connection='local', module_path='%s/' % (ROOT_DIR), forks=100, become=None, become_method=None, become_user=None, check=False,
                    diff=False, listhosts=True, listtasks=False, listtags=False, syntax=False)
    passwords = dict(vault_pass='secret')

    inventory = InventoryManager(loader=loader, sources=[inventory_path])
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    executor = PlaybookExecutor(  
                playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader,  
                options=options, passwords=passwords)  
    results = executor.run()  
    print results

def main():
    ansible_part()

sys.exit(main())

推荐答案

您告诉 Ansible 使用 listhosts=True 列出主机,并且它正在正常工作.

You tell Ansible to list hosts with listhosts=True and it is doing its job properly.

执行对 listhosts=False 的剧本更改.

To execute the playbook change to listhosts=False.

这篇关于以编程方式运行 Ansible playbook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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