基于变量执行角色

Executing roles based on variables

我有一些奇怪的行为。本人还是Ansible新手,提前致歉

我正在尝试根据我在此处看到的示例有条件地执行角色:https://github.com/atomicobject/ansible-laptop-playbook-example/blob/1785f25014fa5a7776de5b332d093b60bf59c8e0/laptop.yml

反正我有一个host_vars/localhost:

has_thing: true

在我的顶级 site.yml 中,我有:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing is defined and has_thing == "true" }

这将跳过该角色。

如果我这样做:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing is defined }

角色执行。

如果我这样做:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing == "true" }

没用。

如果我这样做:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing != "true" }

还是不行。我不明白为什么,变量 has_thing 是明确定义的,因为只要我不测试它的值,它就可以工作。

我在这里错过了什么?

has_thing: true 是一个布尔值,你可以用 has_thing: 'true'.

来测试

但最好更改您的 when 语句以处理布尔值。

P.S。而且你不能有条件地执行一个角色这样一个角色,角色将始终执行,但是when语句将附加到这个角色中的每个任务生成很多输出中跳过的任务数。