Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using {{item}} inside a regexp in a lineinfile task of Ansible

I have a task in an Ansible playbook that is supposed to iterate with a list of users and do a lineinfile to enable access to a postgress database:

- 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

the problem I'm getting is that ansible thinks that the {{item.user}} is not being escaped with "", which actually is not true, since this will expand due to the "" of the whole line. The exact error I get:

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

any ideas on how to do this?

like image 201
sebamontini Avatar asked Mar 17 '17 13:03

sebamontini


People also ask

What is Lineinfile module in Ansible?

The lineinfile is one of the most powerful modules in the Ansible toolbox. Ansible lineinfile module is used to insert a line, modify, remove, and replace an existing line.

How do you replace a line in a file Ansible?

You can use the lineinfile Ansible module to achieve that. The regexp option tells the module what will be the content to replace. The line option replaces the previously found content with the new content of your choice. The backrefs option guarantees that if the regexp does not match, the file will be left unchanged.


1 Answers

first of all, thanks to the guys in IRC on the #ansible channel :)

seems that the issue wasn't with the vars itself but with the un-scaped backslashes

changed the line to: regexp: "^host[\\s\\t]*all[\\s\\t]*{{item.user}}[\\s\\t]*127.0.0.1/32[\\s\\t]*trust" and now it works great

like image 88
sebamontini Avatar answered Sep 20 '22 23:09

sebamontini