It comes packed with a rich collection of modules that allow you to automate and manage nearly any aspect of a system.
One of those available modules is the “posix.patch” modules. In this tutorial, we will learn what this module is, what it does, and how to use it in a real-world playbook.
Ansible Posix.Patch Module
The “posix.patch” module allows us to apply the patch files using the native patch command. If we have a diff file that contains modifications to an existing file or set of files, instead of manually applying those changes, we can use this module to automate the processing of merging the changes.
Module Parameters
The following are some of the parameters that are supported by this module:
src – It specifies the path to the patch file. This file contains the changes to be applied and can be an absolute or a relative path.
Dest – It specifies the path of the file on the remote machine to be patched.
Basedir – It sets the base directory, the root directory where you want to start applying the patch. It defaults to the current working directory.
Strip – It reduces the number of leading directories from the file names in the patch file. For example, a strip level 1 strips the leading directory and dir1/dir/file.txt becomes dir/file.txt.
Backup – This is a Boolean parameter that defines whether to create a backup of the original file before applying the patch. It defaults to false.
State – It sets the desired state after applying the patch. The accepted values include:
- present – apply the patch
- absent – revert the patch
Examples:
Let us explore some examples on how to use this module to apply patches to the files.
Example 1: Basic Usage
Suppose we have a patch file called “version2.diff” that we wish to apply. We can use the patch module as follows:
posix.patch:
src: /home/ubuntu/version2.diff
dest: /var/log/logging.ini
Example 2: Applying a Patch with a Backup
To create a backup before applying a patch, use the backup parameter as follows:
posix.patch:
src: /home/ubuntu/version2.diff
dest: /var/log/logging.ini
backup: yes
Example 3: Reverting a Patch
To revert a patch, we can use the state parameter as follows:
posix.patch:
src: /home/ubuntu/version2.diff
dest: /var/log/logging.ini
state: absent
Example 4: Stripping Directories
If a patch has leading directories and we want to strip one directory from it, we can use the strip parameter as follows:
posix.patch:
src: /home/ubuntu/version2.diff
dest: /var/log/logging.ini
strip: 1
Conclusion
The “posix.patch” module is a straightforward yet powerful tool to automate the patching tasks as you saw in this tutorial. Feel free to check the documentation for more information about this module.