quoting colon in ansible

I am trying to use ansible to check that the output of a particular program is set to a certain value. That value includes a colon followed by a space, and this seems to register as a syntax error no matter how I quote it.

example:

---
- hosts: all
  tasks:
    - raw: echo "something: else"
  register: progOutput

- debug:
    msg: "something else happened!"
  when: progOutput.stdout_lines[-1] != "something: else"

When I run this, I get an error on the first 'raw' command:

ERROR! Syntax Error while loading YAML.


The error appears to have been in '<snip>/test.yml': line 4, column 27, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  tasks:
    - raw: echo "something: else"
                          ^ here

(naturally, my actual use case involved a real program that had a colon in its output, not 'raw: echo'. This was nevertheless the error I saw.)

Clearly, quoting the string in question doesn't fix the problem. I also tried escaping the : with a backslash (\).


Playing around with quoting, I got a helpful error message at last. Apparently, you will confuse the YAML parser unless you quote the entire line.

Here is the working example:

---
- hosts: localhost
  tasks:
    - raw: "echo 'something: else'"
      register: progOutput

    - debug:
        msg: "something else happened!"
      when: 'progOutput.stdout_lines[-1] != "something: else"'

And here is the helpful error message:

ERROR! Syntax Error while loading YAML.


The error appears to have been in '<snip>/test.yml': line 4, column 28, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  tasks:
    - raw: "echo 'something\: else'"
                           ^ here
This one looks easy to fix.  There seems to be an extra unquoted colon in the line
and this is confusing the parser. It was only expecting to find one free
colon. The solution is just add some quotes around the colon, or quote the
entire line after the first colon.

For instance, if the original line was:

    copy: src=file.txt dest=/path/filename:with_colon.txt

It can be written as:

    copy: src=file.txt dest='/path/filename:with_colon.txt'

Or:

    copy: 'src=file.txt dest=/path/filename:with_colon.txt'

It is documented in Ansible's documentation about this.

You can escape colon like this -

- raw: echo "something {{':'}} else"

and output of this is like -

changed: [localhost] => {
    "changed": true,
    "rc": 0,
    "stderr": "",
    "stdout": "something : else\n",
    "stdout_lines": [
        "something : else"
    ]
}