Is there a way to append data using a template module in ansible. There are options for lineinfile and blockinfile in ansible. But I have to append data to the host's file. I want to preserve original hosts and add new hosts to the existing file.
Asked
Active
Viewed 1,413 times
2 Answers
0
When using the template module, a complete file is templated.
What you could do is dynamically build your file in a way like this in the Jinja2 template:
This is content of my file, not being replaced.
{% for item in some_variable %}
{% {{ item }} %}
{% endfor %}
And here is the end of the file, not being replaced.
However, it feels like you're trying to edit a /etc/hosts file or something similar. You shouldn't use template for this use case.
Using lineinfile is perfect for those scenarios. Try something along the lines of:
- name: Add the hosts names and IPs to /etc/hosts
lineinfile:
dest: /etc/hosts
regexp: '.*{{ item }}$'
line: "{{ hostvars[item]['ansible_default_ipv4']['address'] }} {{item}}"
state: present
when: hostvars[item]['ansible_facts']['default_ipv4'] is defined
with_items:
- "{{ groups['all'] }}"

Kevin C
- 4,851
- 8
- 30
- 64
0
You can use blockinfile to accomplish above as below:
- name: Add the below DNS records
blockinfile:
path: /etc/hosts
marker: "------"
insertafter: '^yourlinepattern'
state: present
block: |
lines to append

Santosh Garole
- 1,419
- 13
- 23