Conditional Execution of lineinfile Tasks
In some cases, you may want to execute lineinfile
tasks conditionally, based on the presence or absence of a specific line or pattern in the target file. Ansible provides several ways to achieve this, allowing you to have more control over the modifications made to configuration files.
Using the regexp
Parameter
One way to execute a lineinfile
task conditionally is by using the regexp
parameter. If the specified regular expression pattern is found in the target file, the task will be executed; otherwise, it will be skipped.
- lineinfile:
path: /etc/sysctl.conf
regexp: '^net.ipv4.ip_forward=1'
line: 'net.ipv4.ip_forward=1'
state: present
when: ansible_facts['os_family'] == 'RedHat'
In this example, the lineinfile
task will only be executed if the target system is running a Red Hat-based distribution, as determined by the ansible_facts['os_family']
variable.
Using the check_mode
Parameter
Another way to conditionally execute a lineinfile
task is by using the check_mode
parameter. This parameter allows you to simulate the changes that would be made without actually modifying the target file.
- lineinfile:
path: /etc/nginx/conf.d/default.conf
regexp: '^listen'
line: 'listen 8080;'
state: present
check_mode: yes
register: nginx_config_change
In this example, the lineinfile
task is executed in check mode, and the results are stored in the nginx_config_change
variable. You can then use this variable to conditionally execute other tasks based on whether the configuration file would have been modified.
- debug:
msg: 'The Nginx configuration file would have been modified.'
when: nginx_config_change.changed
By understanding how to conditionally execute lineinfile
tasks, you can ensure that configuration file modifications are only made when necessary, improving the reliability and maintainability of your Ansible playbooks.