Write Ansible playbooks using Python dictionary

蓝咒 提交于 2020-03-03 08:11:10

问题


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'),
        ]
    )

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.

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)"


回答1:


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

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]

You can see it's skipping the second shell task there. However, think about what your playbook does:

  • It checks if the directory is empty
  • If it's not, it disabled everything
  • It install a file into the directory

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.



来源:https://stackoverflow.com/questions/59910992/write-ansible-playbooks-using-python-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!