使用Python字典编写Ansible剧本 [英] Write Ansible playbooks using Python dictionary
问题描述
我正在尝试使用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)"
推荐答案
如果我将您的playbook
词典转换为常规的Ansible剧本,就像这样:
If I convert your playbook
dictionary to a regular Ansible playbook, like this:
- name: Enable Site
hosts:
- localhost
gather_facts: no
tasks:
- action:
module: find
args:
paths: /etc/apache2/sites-enabled
register: files_found
- action:
module: shell
args: cd /etc/apache2/sites-enabled && a2dissite *
register: shell_out
when: files_found.matched > 0
- action:
module: shell
args: a2ensite 100-mysite.conf
register: shell_out
- action:
module: service
args: name='apache2' state='reloaded'
register: shell_out
它似乎按预期运行.也就是说,如果我从一个空的/etc/apache2/sites-enabled
目录开始,我会看到:
It seems to run as intended. That is, if I start with an empty /etc/apache2/sites-enabled
directory, I see:
PLAY [Enable Site] *******************************************************************
TASK [find] **************************************************************************
ok: [localhost]
TASK [shell] *************************************************************************
skipping: [localhost]
TASK [shell] *************************************************************************
changed: [localhost]
您可以看到它正在跳过第二个Shell任务.但是,请考虑一下您的剧本会做什么:
You can see it's skipping the second shell task there. However, think about what your playbook does:
- 它检查目录是否为空
- 如果不是,它将禁用所有功能
- 它将文件安装到目录中
这意味着每次运行此剧本,它都会清空/etc/apache2/sites-enabled
,然后重新启用以site_name
变量命名的站点.
That means every time you run this playbook, it's going to empty out /etc/apache2/sites-enabled
, and then re-enable the site named in your site_name
variable.
这篇关于使用Python字典编写Ansible剧本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!