Search code examples
ansiblelanguage-lawyerquotes

Is there any valid Ansible boolean expression, which would need to be quoted?


Some Ansible task parameters accept complex boolean expressions:

- name: Fail task when both files are identical
  raw: diff foo/file1 bar/file2
  register: diff_cmd
  failed_when: diff_cmd.rc == 0 or diff_cmd.rc >= 2

Is it ever necessary to quote these expressions?


Solution

  • Yes. Take this example from the manual:

    - name: Fail task when the command error output prints FAILED
      command: /usr/bin/example-command -x -y -z
      register: command_result
      failed_when: "'FAILED' in command_result.stderr"
    

    Removing the double quotes triggers the following error:

    ERROR! Syntax Error while loading YAML.
      did not find expected key
    
    The error appears to have been in '/home/alan-sysop/ansible/roles/test/tasks/main.yml': line 4, column 23, but may
    be elsewhere in the file depending on the exact syntax problem.
    
    The offending line appears to be:
    
          register: command_result
          failed_when: 'FAILED' in command_result.stderr
                                ^ here
    This one looks easy to fix.  It seems that there is a value started
    with a quote, and the YAML parser is expecting to see the line ended
    with the same kind of quote.  For instance:
    
        when: "ok" in result.stdout
    
    Could be written as:
    
       when: '"ok" in result.stdout'
    
    Or equivalently:
    
       when: "'ok' in result.stdout"