Ansible lineinfile module syntax error when using multiple variables in string

Issue

I have a few uses of lineinfile in my Ansible playbooks which work well, however my latest addition gives a syntax error and I can’t figure out how to resolve it.

Working code:

  community.windows.win_lineinfile:
    path: C:\PowerTools\Config\Config.psd1
    backrefs: yes
    regex: '^(.*)apiBase(.*)$'
    line: '    apiBase            = "http://{{ app_server }}/dm-rest-services/api"'

Failing code:

  community.windows.win_lineinfile:
    path: C:\PowerTools\Config\Config.psd1
    backrefs: yes
    regex: '^(.*)connectionString(.*)$'
    line: '    connectionString   = "Data Source={{ db_server }},1433;Initial Catalog={{ db_name }};User Id={{ db_user }}; Password={{ dm_db_password['secrets'][0]['secret'] }}"'

I’m getting the below generic syntax error:

ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)

Syntax Error while loading YAML.
  expected <block end>, but found '<scalar>'

The error appears to be in '/root/gitlab-ansible/roles/fico_etl/tasks/powertools.yml': line 25, column 152, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

    regex: '^(.*)connectionString(.*)$'
    line: '    connectionString   = "Data Source={{ db_server }},1433;Initial Catalog={{ db_name }};User Id={{ db_user }}; Password={{ dm_db_password['secrets'][0]['secret'] }}"'
                                                                                                                                                       ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

Any guidance would be much appreciated.

Solution

The problem is that you’re using single quotes (‘) around the entire line, but also within the line around 'secrets' and 'secret'.

In your case, you need to use double quotes around the whole line, and escape the double quotes within the line with a backslash

  community.windows.win_lineinfile:
    path: C:\PowerTools\Config\Config.psd1
    backrefs: yes
    regex: '^(.*)connectionString(.*)$'
    line: "    connectionString   = \"Data Source={{ db_server }},1433;Initial Catalog={{ db_name }};User Id={{ db_user }}; Password={{ dm_db_password['secrets'][0]['secret'] }}\""

Answered By – olambert

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published