1

I am trying to write the following string with Ansible lininfile.

The failing Ansible task:

- name: Insert GetInterfaceIP
  lineinfile:
    path: /etc/consul.d/consul.hcl
    regexp: '^advertise'
    line: advertise_addr = "{{ GetInterfaceIP `eth0` }}"

Desired result in the file:

advertise_addr = "{{ GetInterfaceIP `eth0` }}"

How can I escape the special characters so that the line is written to the file exactly like this?

U880D
  • 8,601
  • 6
  • 24
  • 40
fmnbg
  • 15
  • 2

1 Answers1

0

To prevent the given string from Templating, you might take advantage from Unsafe or raw strings.

The following example will add the exact string into the file

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Add unsafe text line
    lineinfile:
      path: test.txt
      line: !unsafe 'advertise_addr = "{{ GetInterfaceIP `eth0` }}"'

resulting into an output of

tail -1 test.txt
advertise_addr = "{{ GetInterfaceIP `eth0` }}"

since

Marking data as unsafe prevents malicious users from abusing Jinja2 templates to execute arbitrary code on target machines. The Ansible implementation ensures that unsafe values are never templated.

Similar Q&A

U880D
  • 8,601
  • 6
  • 24
  • 40
  • 1
    Thank you very much, this works perfectly! Unfortunately I can't upvote your answer because of this message from stackoverflow: Thanks for the feedback! You need at least 15 reputation to cast a vote, but your feedback has been recorded. – fmnbg Sep 24 '22 at 10:59
  • But you can accept it as answer if it answer your question and resolve the problem. By doing this you'll gain also reputation. – U880D Sep 24 '22 at 19:22
  • Sorry, I hadn't seen the check mark. :) – fmnbg Sep 25 '22 at 20:44