如何在 'when' 模块中包含特殊字符?

How to include special characters in the 'when' module?

下面的变量error_code包含这个字符串:

"failed": true

如何使用此字符串作为“when”模块的触发器?我不确定如何转义这些特殊字符,以便剧本正确解释它们。这是我尝试过但没有用的方法:

  - name: copying index
    copy: 
      src: /tmp/index.html
      dest: /var/www/html/
    notify: reloadone
    register: error_code
  - name: verify content
    fail:
      msg: There has been an error with the index file
    when: " \"failed\"\: true in error_code"
  handlers:
  - name: reloadone
    systemd:
      state: restarted
      name: httpd

将字符串放入single-guotes,例如

- hosts: localhost
  gather_facts: false
  vars:
    error_code: '"failed": true'
  tasks:
    - debug:
        var: error_code
    - name: verify content
      fail:
        msg: There has been an error with the index file
      when: error_code == result
      vars:
        result: '"failed": true'

给予

TASK [debug] ******************************************************
ok: [localhost] => 
  error_code: '"failed": true'

TASK [verify content] *********************************************
fatal: [localhost]: FAILED! => changed=false 
  msg: There has been an error with the index file

下一个选项是将字符串转换为字典并测试属性的布尔值失败,例如

- hosts: localhost
  gather_facts: false
  vars:
    error_code: '"failed": true'
  tasks:
    - debug:
        var: error_code|from_yaml
    - name: verify content
      fail:
        msg: There has been an error with the index file
      when: result.failed
      vars:
        result: "{{ error_code|from_yaml }}"

给予

TASK [debug] ****************************************************
ok: [localhost] => 
  error_code|from_yaml:
    failed: true

TASK [verify content] *******************************************
fatal: [localhost]: FAILED! => changed=false 
  msg: There has been an error with the index file

如果代码没有失败

    error_code: '"failed": false' 

条件将被跳过

TASK [debug] *****************************************************
ok: [localhost] => 
  error_code|from_yaml:
    failed: false

TASK [verify content] ********************************************
skipping: [localhost]