首页 > 解决方案 > Ansible 在“何时”条件下警告模板变量作为字符串的一部分

问题描述

我有以下 Ansible 任务,该任务旨在当且仅当“nginx -v”的输出与预期不匹配时运行 nginx 编译脚本。

- name: get nginx version
  command: "{{ nginx_binary }} -v"
  register: result
  ignore_errors: True

- name: download and compile nginx
  include: install.yml
  when: result.rc != 0 or result.stderr != "nginx version{{':'}} nginx/{{nginx_version}}"

当我使用最新版本的 Ansible 运行它时,我得到:

[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}. 
Found: result.rc != 0 or result.stderr != "nginx version{{':'}}
nginx/{{nginx_version}}"

我对如何在没有模板分隔符的情况下编写此语句感到困惑。如果我删除冒号字符周围的模板变量,我会得到:

- name: download and compile nginx
  include: install.yml
  when: result.rc != 0 or result.stderr != "nginx version: nginx/{{nginx_version}}"

我得到:

Syntax Error while loading YAML.
  mapping values are not allowed in this context

The error appears to be in '/Users/kevin/src/github.com/kevinburke/web-deployment/roles/nginx/tasks/main.yml': line 13, column 58, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  include: install.yml
  when: result.rc != 0 or result.stderr != "nginx version: nginx/{{nginx_version}}"
                                                         ^ here
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 }}"

我也试过这个,但我仍然收到警告:

- name: download and compile nginx
  include: install.yml
  when: result.rc != 0 or result.stderr != "nginx version: nginx/" + nginx_version

有什么建议么?似乎如果他们对此发出警告,应该有一种方法可以删除警告,但到目前为止我还没有找到它。

标签: ansibleyaml

解决方案


将字符串放入变量中,例如

    - name: get nginx version
      command: nginx -v
      register: result
      ignore_errors: True

    - debug:
        var: result.stderr

    - name: 'download and compile nginx {{ nginx_version }}'
      debug:
        msg: "include: install.yml"
      when: result.stderr != _nginx_version
      vars:
        nginx_version: '1.18.0'
        _nginx_version: 'nginx version: nginx/{{ nginx_version }}'

    - name: 'download and compile nginx {{ nginx_version }}'
      debug:
        msg: "include: install.yml"
      when: result.stderr != _nginx_version
      vars:
        nginx_version: '1.18.1'
        _nginx_version: 'nginx version: nginx/{{ nginx_version }}'

TASK [debug] ***************************************************************
ok: [srv] => 
  result.stderr: 'nginx version: nginx/1.18.0'

TASK [download and compile nginx 1.18.0] ***********************************
skipping: [srv]

TASK [download and compile nginx 1.18.1] ***********************************
ok: [srv] => 
  msg: 'include: install.yml'

推荐阅读