Shyam Jos
Shyam Jos

Reputation: 231

How to escape special characters in ansible shell module

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

Upvotes: 9

Views: 31704

Answers (2)

Alvaro Ni&#241;o
Alvaro Ni&#241;o

Reputation: 567

Consider that escape caracter is \ not /

EDIT

Your problem is not related to escape character, it is caused your sed expression has an additional /

sed 's/Date: ///g'

Should be writen like sed 's/foo/bar/g'

In your case sed 's/Date: //g'

Upvotes: -1

tinita
tinita

Reputation: 4336

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.

Upvotes: 15

Related Questions