3

In my playbook the following line should return 1, and if it returns >1, the play should stop:

shell: ls -l /opt/tomcat/|grep "[ ]\+{{ newTomcatVer }}$"; echo $?

My play did indeed fail with this error:

"msg": "There is more than one /opt/tomcat/apache-tomcat-8.x.xx instance on server01, ending play"

After running again with in debug mode, I see this shell command is being represented like this in the debug output:

"cmd": "ls -l /opt/tomcat/|grep \"[ ]\\+apache-tomcat-8.5.69$\"; echo $?",

In the above, double quotes are escaped with \ character. The question is, which command is actually being used - the one that is in the playbook, or the one which we see in the debug output?

Because if I run the command which is in the notebook, i.e. without escape chars, the output is 1 as expected:

[tomcat@server01 ~]$ ls -l /opt/tomcat/|grep "[ ]\\+apache-tomcat-8.5.69$"; echo $?
1

But if I issue the command which is in the debug output, I get this:

[tomcat@server01 ~]$ ls -l /opt/tomcat/|grep \"[ ]\\+apache-tomcat-8.5.69$\"; echo $?
grep: Invalid regular expression
2

Any ideas how to solve this?

kamokoba
  • 133
  • 1
  • 5

1 Answers1

4

Use single quotes in the grep command.

grep "[ ]\+{{ newTomcatVer }}$"

When you use double quotes, the shell will try to do variable expansion, meaning it will try to make sense of $". This is coming out as $\" because the shell doesn't recognize $" as a parameter it can expand, so it tries to guess what you wanted and escapes the quotation mark.

There's no real reason to do shell parameter expansion here, so you can place the regex in single quotes to solve the problem. The shell will not attempt to do parameter expansion and will treat the $ literally.

grep '[ ]\+{{ newTomcatVer }}$'
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972