首页 > 解决方案 > 在字符串中使用多个变量时,Ansible lineinfile 模块语法错误

问题描述

我在我的 Ansible 剧本中使用了一些 lineinfile,它们运行良好,但是我最新的添加给出了语法错误,我不知道如何解决它。

工作代码:

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

失败代码:

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

我收到以下通用语法错误:

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 }}"

任何指导将不胜感激。

标签: windowssyntaxansible

解决方案


问题是您在整行周围使用单引号 ('),但也在'secrets'and周围的行内使用单引号 (') 'secret'

在您的情况下,您需要在整行周围使用双引号,并用反斜杠转义行内的双引号

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


推荐阅读