Ansible, the Private detective
Table of contents
Deployments can be automated with Jenkins but when it comes to replacing the version number in the application.properties file / adding a new line to it - Ansible can be useful to change things in remote files. This blog will explain how to replace a word in a string & add a new line in a file.
Ansible enters into other machines, & does tasks specified by us so it's an Private detective.
Replace module -
It's used to replace a word in a string.
---
- name: Replace version number in file with user input
hosts: app
vars:
- new_version: "1.0.0.0"
tasks:
- name: Replace version number in the file
replace:
path: /home/test/Application/app/application.properties
regexp: 'app_version:S\d+\.\d+\.\d+\.\d+'
replace: 'app_version:S{{ new_version }}'
In the vars section, we have defined a variable - new_version. (1.0.0.0 is the default value)
In the tasks section, we have used Ansible's replace module parameters like path to specify our file path, and regexp to identify our line & replace parameter is used to add a new version.
Note:- We are taking new_version from user input
ansible-playbook file-name.yml --e "new_version=1.0.0.1"
So, now the version number will be changed to 1.0.0.1
lineinfile module -
It's used to add, delete, modify any line in a remote file. Here we will use it to add a new line.
---
- name: Addding a line to configuration file
hosts: app
vars:
line_to_add: "new_app_version:S1.0.0.0"
file_path: /home/test/Application/app/application.properties
tasks:
- name: Add the line to the file if it doesn't exist
lineinfile:
path: "{{ file_path }}"
line: "{{ line_to_add }}"
state: present
Here, 2 variables in the vars section - line_to_add have the new line to be added & file_path to specify the path.
In the task section, we have just called these variables. state: present will check if the line already exists, if yes, it won't make any changes, if no, then it will make the changes specified.
Note:- Our hosts are mentioned in the default location - /etc/ansible/hosts file.
[app]
IP ansible_ssh_pass=test ansible_ssh_user=test
Here, ansible will be using the username-test to make changes to this file.
Also, in ansible.cfg file add this line -
[defaults]
host_key_checking = false
Remember when we ssh into other machines, there's a thing like save this remote machine's fingerprint - Add this line so that ansible playbook can ssh into specified machines & perform these tasks.
Thank you.