jto
jto

Reputation: 185

Ansible lineinfile module syntax error when using multiple variables in string

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.

Upvotes: 0

Views: 423

Answers (1)

olambert
olambert

Reputation: 1115

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'] }}\""

Upvotes: 1

Related Questions