briconaut
briconaut

Reputation: 324

How to build a configuration with templates/blockinfile/lineinfile in a modular manner

I'm trying to assemble an iptables file suitable for iptables-restore using multiple roles:

Playbooks are supposed to import the role setup-iptables first and then import the smaller roles that are needed to configure the host.

My problem is, that this file gets recreated every time the playbook is run. This is potentially dangerous if the play gets interupted and the incomplete rules get applied. Also it's ugly because ansible will show changes to the host, even if the resulting file is identical to its original state.

Simply working with lineinfile and blockinfile from the beginnning is not an option because the iptable rules are highly dependend on the ordering of the rules. The initial template is required because it provides a lot of 'markers'. These markers are then used by the lineinfile statements of the subsequent roles to corretly position their rules.

My current workaround idea is to assemble the file locally and at the end of the play 'flush' it to the remote host.

Is there a better way? What's the 'ansible way' to do this?

Upvotes: 0

Views: 380

Answers (1)

Kelson Silva
Kelson Silva

Reputation: 532

You can check the file exists and if it does, skip recreating it...

- name: check if the file exists
  stat:
    path: /etc/sysconfig/iptables #Example path
  register: iptables_file

- name: Create the file if it doesnt exists
  copy:
    content: "your initial rules"
    dest: /etc/sysconfig/iptables
  when: iptables_file.stat.exists == False

Upvotes: 1

Related Questions