How to escape special characters in ansible shell module
One of the problems here is the colon followed by a space :
. This is usually an indicator for a mapping key.
YAML does not allow nested mappings on one line, e.g.:
foo: bar: baz
That's why YAML designers chose to forbid :
in a mapping value if it's on the same line as the key. (It could have been been solved as well by simply ignoring further occurances and treat that as regular content.)
You have several choices. You can just put the whole value in quotes, which is not a good idea in this case since you have both single and double quotes which you would have to escape then.
A workaround can be to escape the space in the sed command:
shell: date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date:\ //g') +0530"
A more general solution is to use a folded block scalar:
shell: >
date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date: //g') +0530"
You could even seperate this into several lines now, because the folded block scalar will fold consecutive lines into one:
shell: >
date -s "$(curl -s --head http://google.com
| grep '^Date:' | sed 's/Date: //g') +0530"
The second problem is, as Javier mentioned, the sed expression s/Date/: //g
. You probably want s/Date: //g
. Also look at the suggestion by @tripleee how to improve your command.

Comments
-
Shyam Jos 6 months
I tried bash escape and double quotes methods to escape the special characters in below shell command, But both didn't work, What is the proper way to escape special characters in ansible playbook?
The offending line appears to be: name: Syncing system date with htpdate failed!, Trying wget method... shell: date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date: //g' ) +0530" ^ here exception type: <class 'yaml.scanner.ScannerError'> exception: mapping values are not allowed in this context in "<unicode string>", line 15, column 93
-
Javier Elices almost 5 yearsI think that your reply should be a comment. It does not propose an answer to the question. Besides, I don't see anything that needs escaping. He has used double quotes for the bigger quote, then single quotes inside that.
-
tripleee almost 5 yearsI'm guessing the answerer is unfamiliar with
sed
and imagined that the slash delimiters insed 's/foo/bar/'
were supposed to be backslashes. -
Shyam Jos almost 5 yearsThank you so much, folded block scalar solution fixed my issue
-
Shyam Jos almost 5 years@alvaro-nino that extra slash was a typo, corrected it now
-
Jean-Marc Amon over 2 yearsThanks, my issue is fixed with folded block