...

Ansible Blockinfile Module: A Master Guide with 5 Use Cases and how to avoid 2 mistakes

5/5 - (1 vote)

Introduction

The Ansible blockinfile module simplifies the management of text blocks within files, enabling seamless insertion, modification, or removal of specific content. This powerful tool allows users to manipulate files by adding or altering specific text sections, providing fine-grained control over configurations. Employing this module streamlines configuration file management, facilitating targeted updates while maintaining the integrity of existing content. The blockinfile module proves invaluable in scenarios where precise edits or additions are necessary within configuration files, enabling automation and consistency across diverse systems or environments.

Prerequisites

General Example of Ansible blockinfile module

The below example is self-explanatory. Just read the comments at the end of the line.

---
- name: Insert block of text into a configuration file
  hosts: your_target_host
  tasks:
    - name: Insert block of text into a configuration file
      blockinfile:
        path: /path/to/your/config/file.conf  # Specify the path of the configuration file
        block: |
          # This is the block of text to be inserted
          # You can add multiple lines here
          # This example demonstrates inserting a block of text
          # into a configuration file using Ansible blockinfile module
        marker: "# START ANSIBLE MANAGED BLOCK"  # Define a unique marker for the block
        state: present  # Set 'present' to insert the block (or 'absent' to remove it)
        insertbefore: EOF  # Define a unique string or pattern where the block should be inserted

Main Use cases of blockinfile module in Ansible

Ansible Blockinfile module
Ansible Blockinfile Module

1. Configuration File Updates:

Use blockinfile to insert or modify specific sections of configuration files, such as appending environment variables or modifying authentication parameters within system configuration files.

- name: Insert/update environment variables in a configuration file
  hosts: your_target_host
  tasks:
    - name: Insert environment variables into a configuration file
      blockinfile:
        path: /path/to/your/config/file.conf
        block: |
          # Inserted by Ansible - Environment Variables
          ENV_VAR1=value1
          ENV_VAR2=value2
        marker: "# START ANSIBLE MANAGED BLOCK"
        state: present
        insertbefore: EOF

2. Managing Firewall Rules:

Employ blockinfile to add or modify firewall rules in configuration files, ensuring precise control over allowed or blocked ports and IPs within firewall settings.

- name: Insert/update firewall rules in configuration file
  hosts: your_target_host
  tasks:
    - name: Add firewall rules into a configuration file
      blockinfile:
        path: /path/to/your/firewall/config.conf
        block: |
          # Inserted by Ansible - Firewall Rules
          ALLOW_PORT_80=127.0.0.1
          DENY_PORT_22=192.168.1.1
        marker: "# START ANSIBLE MANAGED BLOCK"
        state: present
        insertbefore: EOF

3. Managing Software Repositories:

Utilize blockinfile to update package repository configurations by inserting new repository URLs or modifying existing repository entries within package manager configuration files.

- name: Update package repository configurations
  hosts: your_target_host
  tasks:
    - name: Add repository entries into package manager configuration
      blockinfile:
        path: /etc/apt/sources.list
        block: |
          # Inserted by Ansible - Package Repositories
          deb http://new.repo.example.com/ubuntu focal main
        marker: "# START ANSIBLE MANAGED BLOCK"
        state: present
        insertbefore: EOF

4. Template File Management:

Employ blockinfile to modify template files, insert custom snippets or update specific sections, ensuring consistency and customization while deploying configurations across multiple systems.

- name: Update template file with custom snippets
  hosts: your_target_host
  tasks:
    - name: Insert custom snippets into template file
      blockinfile:
        path: /path/to/your/template/file.conf.j2
        block: |
          # Inserted by Ansible - Custom Snippets
          {% block custom_block %}
          Custom configuration snippet here
          {% endblock %}
        marker: "# START ANSIBLE MANAGED BLOCK"
        state: present
        insertbefore: EOF

5. Managing Web Server Configurations:

Use blockinfile to insert or update sections in web server configuration files, such as virtual host configurations or SSL certificate settings, enabling controlled updates to web server settings.

- name: Update web server configuration file
  hosts: your_target_host
  tasks:
    - name: Insert/update virtual host configurations
      blockinfile:
        path: /etc/apache2/sites-available/your_website.conf
        block: |
          # Inserted by Ansible - Virtual Host Configurations
          <VirtualHost *:80>
              ServerName example.com
              DocumentRoot /var/www/html/example
              # other configurations...
          </VirtualHost>
        marker: "# START ANSIBLE MANAGED BLOCK"
        state: present
        insertbefore: EOF

Common mistakes when using the blockinfile module

Mistake 1: Missing begin_marker and end_marker when using multiple blockinfile modules for the same file.

- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth0 inet static
          address 192.0.12.23
          netmask 255.255.255.0
    
- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth1 inet static
          address 192.0.12.24
          netmask 255.255.255.0

Output: The last blockinfile will override all prior blockinfile module tasks if we don’t specify a unique begin_marker and end_marker for each blockinfile module.

Actual change in /etc/network/interfaces will be from second task only

# BEGIN ANSIBLE MANAGED BLOCK #
iface eth1 inet static
   address 192.0.12.24
    netmask 255.255.255.0
# END ANSIBLE MANAGED BLOCK #

Solution:

Specify unique begin_marker and end_marker for each blockinfile module

- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth0 inet static
          address 192.0.12.23
          netmask 255.255.255.0
    being_marker: begin eth0 ethernet
    end_marker: end eth0 ethernet
    
- name: Insert/Update eth1 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth1 inet static
          address 192.0.12.24
          netmask 255.255.255.0
    being_marker: begin eth1 ethernet
    end_marker: end eth1 ethernet

Output

Actual change in /etc/network/interfaces will be from second task only

# begin eth0 ethernet ANSIBLE MANAGED BLOCK #
iface eth0 inet static
   address 192.0.12.23
    netmask 255.255.255.0
# end eth0 ethernet ANSIBLE MANAGED BLOCK #
# begin eth1 ethernet ANSIBLE MANAGED BLOCK #
iface eth1 inet static
   address 192.0.12.24
    netmask 255.255.255.0
# end eth1 ethernet ANSIBLE MANAGED BLOCK #

Mistake 2: Same begin_marker and end_marker when using multiple blockinfile modules for the same file.

- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth0 inet static
          address 192.0.12.23
          netmask 255.255.255.0
    being_marker: begin ethernet
    end_marker: end ethernet
    
- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth1 inet static
          address 192.0.12.24
          netmask 255.255.255.0
    being_marker: begin ethernet
    end_marker: end ethernet

Output: The last blockinfile will override all prior blockinfile module tasks if we don’t specify a unique begin_marker and end_marker for each blockinfile module.

Actual change in /etc/network/interfaces will be from second task only

# begin ethernet ANSIBLE MANAGED BLOCK #
iface eth1 inet static
   address 192.0.12.24
    netmask 255.255.255.0
# end ethernet ANSIBLE MANAGED BLOCK #

Solution:

Specify unique begin_marker and end_marker for each blockinfile module

- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth0 inet static
          address 192.0.12.23
          netmask 255.255.255.0
    being_marker: begin eth0 ethernet
    end_marker: end eth0 ethernet
    
- name: Insert/Update eth1 configuration stanza in /etc/network/interfaces
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth1 inet static
          address 192.0.12.24
          netmask 255.255.255.0
    being_marker: begin eth1 ethernet
    end_marker: end eth1 ethernet

Output

Actual change in /etc/network/interfaces will be from second task only

# begin eth0 ethernet ANSIBLE MANAGED BLOCK #
iface eth0 inet static
   address 192.0.12.23
    netmask 255.255.255.0
# end eth0 ethernet ANSIBLE MANAGED BLOCK #
# begin eth1 ethernet ANSIBLE MANAGED BLOCK #
iface eth1 inet static
   address 192.0.12.24
    netmask 255.255.255.0
# end eth1 ethernet ANSIBLE MANAGED BLOCK #

Reference:

FAQs

What is the Ansible blockinfile module used for?
The blockinfile module manages blocks of text within files, allowing you to insert, update, or remove text blocks dynamically.

How can I ensure my block only appears once in a file?
Set marker tags uniquely and define the state: present to add or absent to remove a block if it exists.

Can blockinfile append content without replacing existing blocks?
Yes, use insertbefore or insertafter options to control placement without overwriting.

How do I use blockinfile with dynamic content?
You can use Ansible variables within the block text for dynamic updates.

What are common issues when using blockinfile?
Misconfigured markers or incorrect path can cause errors. Make sure paths are valid and markers are distinct.

Conclusion


The Ansible blockinfile module proves to be a powerful tool for managing text blocks within configuration files. Its ability to insert, modify, or remove specific content simplifies configuration management across diverse systems. Offering precision and ease, this module streamlines the automation of targeted edits while preserving existing file structures. Providing a controlled method for handling text blocks enhances configuration file management, ensuring consistency and accuracy in system configurations. The blockinfile module is a valuable asset in Ansible’s arsenal, empowering users to efficiently and effectively manage and maintain configuration files in complex environments.

In this post, we learned about general use cases of the blockinfile module, common mistakes, pitfalls, and their solution.

Spread the love

Leave a Comment

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.