Ansible:带有空变量的条件 "when" 子句

Ansible: Conditional "when" clause with empty variable

我的任务是创建一个 Ansible 角色,我在同一角色的 defaults/main.yml 文件中设置了一个变量。

role_variable: ""

然后在另一个任务中调用此变量,该任务将其用作条件,以执行操作:

角色

-name: "Task which is called" 
   # Stuff which will be done given that the conditional below is correct
   set_fact:
      role_variable: "{{ variable_1 if 'string' not in issuer else variable_2 }} "
 when: (role_variable | length == 0)

在剧本中,这个变量不是 set 其他任何地方 - 它仅用于调试 - 如果我打印上面的内容debug 子句中的条件,它正确 returns 0.

剧本

-name: "Import secrets" 
   vars_files: 
     - secrets.yml
hosts: "{{ target }}"
gather_facts: false

tasks:
   - include_vars:
      file: "{{ credentials }}"
   - ansible.builtin.setup:
     gather_subset: min ### This is used in other parts of the complete playbook
   delegate_to: localhost

   - name: "Task to call"
      import_role: 
         name: role_name
         tasks_from: role_task_name

当此变量未在剧本中设置值时,它会正确计算,例如: ansible-playbook playbook.yaml -e ""

但无论何时,即使使用空字符串(例如)对其进行评估:

ansible-playbook playbook.yaml -e "role_variable="

例如在 Jenkins 构建中这是必需的,用户可以传递或不传递此变量。如果没有,它应该使用默认值,在角色或游戏中编写脚本。

我尝试了其他方法来做同样的事情:

when: role_variable is none

when: role_variable is null

when: role_variable is none

when: role_variable is match("")

到目前为止,我没有运气。

objective是将role_variable默认传给一个空字符串"",只有当该变量为空时才重新设置

有没有人有过这方面的经验,如何使这项工作成为可能?

提前感谢您的帮助

你必须做这个测试:

- name: "Task which is called" 
  debug: msg="ok"
  when: role_variable is not defined or role_variable == ''

如果 role_variable 未定义或 role_variable 为空,您将看到执行的任务

针对您的问题

- hosts: localhost
  gather_facts: no
  tasks:   
    - name: loop over
      pause: 
        prompt: "role_variable is empty, give the content " 
      when: role_variable is not defined or role_variable == ''
      register: out

    - name: "Task which is called" 
      set_fact:
        role_variable: "{{ out.user_input }}"
      when: out.user_input is defined

    - name: display
      debug: 
        msg: "{{ role_variable }}"

但似乎结果是空的...启动时 ansible-playbook playbook.yaml -e "role_variable=" 我不知道它是否有错误

我验证了 - 也感谢做出贡献的人 - 我试图实现的目标实际上是不可能的。

根据Ansible documentation,使用--extra-vars-e标志设置变量优先于设置变量。

即使是定义它并将其留空的单一行为,也只会触发条件,并且无法覆盖它。

在我的例子中,因为我必须通过 .groovy 文件将它传递给 Jenkins,所以我设置了一个条件,当变量为空时,我指示它不传递参数。