在 Ansible 任务变量中使用条件


- roles
  - consul
    - vars/main.yml

main.yml,我尝试:

consul_is_server: {{ true if consul_server is defined else false }}

和剧本:

- hosts: consul-server
  roles:
    - consul
  vars:
    consul_server: true

出现错误:

consul_is_server: {{ "true" if consul_server is defined else "false" }}
                            ^
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:
    with_items:
      - {{ foo }}
Should be written as:
    with_items:
      - "{{ foo }}"

如何在任务变量中使用条件?

Vars 文件并不意味着包含条件,它们应该只包含变量。条件用于剧本的任务部分。

vars:
  consul_server: true

然后,条件执行可能如下所示:

tasks:
  - shell: echo "This certainly is consul_server!"
    when: consul_server

现在它工作了:

consul_is_server:  >
    {{ true  if consul_server is defined and consul_server==true else false }}

但在这种情况下consul_is_server是字符串:"假"或"真"。

因此,在模板中使用此变量时,我需要使用 cast 来bool

"server": {{ "true" if consul_is_server |bool else "false" }}

相关内容

  • 没有找到相关文章

最新更新