ku4eto
ku4eto

Reputation: 326

Character escape single quote in a string in Expect Module

i have created a .YML Playbook.

Put some code in it, works fine.

Then i am hit with an issue - i am trying to automate the deployment of a certain application. The application prompts for user interaction. Unfortunatelly, "yes | command" does not work. It simply gets ignored, and still prompts.

So, i decided to use the Expect Module.

Current code looks like this:

- hosts: all
  remote_user: someuser
  gather_facts: yes

  tasks:
    - name: "Copy files"
      copy: src=../somefiles/ dest=/tmp

    - name: "Execute some script"
      shell: sudo /tmp/script.sh

    - name: "Execute app"
      expect:
        command: /bin/bash -c 'sudo /tmp/app arguments'
        responses:
        "'Press 'y' to confirm ('s' to skip, 'a' to abort):'": "y"
      echo: y

I have encassed the Expected line, in double quotes. But, since the Expected Line, has Single quotes ('), it seems to be breaking the syntax.

The error output is as follow:

ERROR! Syntax Error while loading YAML.


The error appears to have been in 'deploy.yml': line 16, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

        responses:
        "'Press 'y' to confirm ('s' to skip, 'a' to abort):'": "y"
^ 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"
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes.  If starting a value with a quote, make sure the
line ends with the same set of quotes.  For instance this arbitrary
example:

    foo: "bad" "wolf"

Could be written as:

    foo: '"bad" "wolf"'

I have tried both with backslash () to do character escaping for the single quotes, and double quoting the single quotes. None of them worked. Depending on the order of the quotes i place, i either get This one looks easy to fix. or straight to bad wolf.

Upvotes: 0

Views: 1771

Answers (1)

Ignacio Millán
Ignacio Millán

Reputation: 8026

Problem are not quotes but special characters in the string. Expect module performs a regex matching, so the response string must be regex-compliant

That means special characters as parenthesis and commas must be escaped

The working example is like that:

/tmp/run.sh:

#!/bin/bash
echo "Press 'y' to confirm ('s' to skip, 'a' to abort):"
read response
echo $response

ansible playbook:

- connection: local
  hosts: localhost
  tasks:
    - name: "Execute app"
      expect:
        command: /tmp/run.sh
        responses:
          Press 'y' to confirm \('s' to skip\, 'a' to abort\):: "y"
        echo: yes

Upvotes: 1

Related Questions