在Ansible的lineinfile任务中的regexp中使用{{item}}

时间:2017-03-17 13:55:47

标签: ansible yaml 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

我得到的问题是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 }}"

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

1 个答案:

答案 0 :(得分:3)

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

似乎问题不在于变量本身,而在于未使用反斜杠

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