How to write tick marks and brackets with Ansible 'lineinfile' module?

Viewed 22

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?

1 Answers

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

Related