使用 Python 字典编写 Ansible playbook [英] Write Ansible playbooks using Python dictionary

查看:35
本文介绍了使用 Python 字典编写 Ansible playbook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 脚本执行以下剧本.

I am trying execute the following playbook using python script.

playbook = dict(
        name = "Enable Site",
        hosts = [host],
        gather_facts = 'no',
        tasks = [
            dict(action=dict(
                module='find', args=dict(paths="/etc/apache2/sites-enabled")), register='files_found'),
            dict(action=dict(
                module='shell', args="cd /etc/apache2/sites-enabled && a2dissite *"), register='shell_out', when='files_found.matched > 0'),
            dict(action=dict(module='shell', args="a2ensite " + site_name), register='shell_out'),
            dict(action=dict(module='service', args="name='apache2' state='reloaded'"), register='shell_out'),
        ]
    )

此剧本基本上检查是否启用了任何 apache 站点(如果是),然后通过从/etc/apache2/sites-enabled 中删除所有文件来禁用它们.

This playbook basically checks if any apache site is enabled if yes then it disables them by removing all the files from /etc/apache2/sites-enabled.

第二个任务应该在目录 /etc/apache2/sites-enabled 为空时执行.但是何时"条件总是被评估为真.即使我写了 when="False".也试过 when="eval(False)"

The second task is supposed to be executed when the directory /etc/apache2/sites-enabled is empty. But the "when" the condition is always evaluated to be true. Even if I write when="False". Also tried when="eval(False)"

推荐答案

这个问题已经很老了,但是您可以找到 ansible 如何解释剧本,但使用您尝试使用的 api:每个实例:

this question is rather old but you can find how ansible interprets the playbook but using the api you tried to use: per instance:

#!/usr/bin/python

import json
from ansible import context
from ansible import constants as C
from ansible.playbook import Playbook
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager

loader=DataLoader()
variable_manager = VariableManager(loader=loader)


pb = Playbook.load('pb.yml', variable_manager=variable_manager, loader=loader)
print(json.dumps(pb._loader.__dict__['_FILE_CACHE']['/usr/ansible/pb.yml'][0], indent=2))

这将以 json 格式输出剧本.然后你可以将它与 python api 或 ansible-runner 一起使用.

this will output the playbook in json format. then you can use it with the python api or with ansible-runner.

请注意,API 必然会更改,恕不另行通知,因此这可能在未来版本中不起作用..在 RHEL7 上使用 ansible 2.9 进行测试.

note the API is bound to change without notice so this may not work in future versions. . tested with ansible 2.9 on RHEL7.

这篇关于使用 Python 字典编写 Ansible playbook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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