在 Ansible 的 lineinfile 任务中的正则表达式中使用 {{item}}

seb*_*ini 5 yaml ansible ansible-2.x

我在 Ansible playbook 中有一个任务,该任务应该迭代用户列表并执行 lineinfile 以启用对 postgress 数据库的访问:

- name: Postgres localhost access
  lineinfile:
    dest: "{{postgres_dest}}/data/pg_hba.conf"
    line: "host    all             {{item.user}}   127.0.0.1/32            trust"
    regexp: "^host[\s\t]*all[\s\t]*{{item.user}}[\s\t]*127.0.0.1/32[\s\t]*trust"
    insertbefore: EOF
  with_items: "{{postgres_users}}"
  notify: postgres reload
  tags:
    - postgres
    - postgres_hba
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是 ansible 认为{{item.user}}没有被 转义"",这实际上是不正确的,因为这会由于""整行的扩大。我得到的确切错误:

Syntax Error while loading YAML script, jenkins.yml
Note: The error may actually appear before this position: line 156, column 9

        line: "host    all             {{item.user}}   127.0.0.1/32            trust"
        regexp: "^host[\s\t]*all[\s\t]*{{item.user}}[\s\t]*127.0.0.1/32[\s\t]*trust"
        ^
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 }}"
Run Code Online (Sandbox Code Playgroud)

关于如何做到这一点的任何想法?

seb*_*ini 5

首先,感谢#ansible 频道上 IRC 的那些人:)

似乎问题不在于 vars 本身,而在于 un-scaped 反斜杠

将行更改为: regexp: "^host[\\s\\t]*all[\\s\\t]*{{item.user}}[\\s\\t]*127.0.0.1/32[\\s\\t]*trust" 现在效果很好