Practical Use Cases and Examples
Updating Configuration Files
One common use case for updating file content on remote hosts using Ansible is to manage configuration files. For example, you can use Ansible to update the Apache configuration file (/etc/apache2/apache2.conf
) to enable or disable specific modules, or to update the Nginx configuration file (/etc/nginx/conf.d/default.conf
) to change the server name or document root.
Here's an example of using Ansible to update the Apache configuration file:
- hosts: webservers
tasks:
- name: Update the Apache configuration
lineinfile:
path: /etc/apache2/apache2.conf
regexp: "^ServerName"
line: "ServerName example.com"
state: present
- name: Restart Apache
service:
name: apache2
state: restarted
This Ansible Playbook will update the ServerName
directive in the Apache configuration file and then restart the Apache service on all the hosts in the webservers
group.
Updating Environment Variables
Another common use case for updating file content on remote hosts is to manage environment variables. For example, you can use Ansible to update the .bashrc
file on remote hosts to set or modify environment variables.
Here's an example of using Ansible to update the JAVA_HOME
environment variable in the .bashrc
file:
- hosts: all
tasks:
- name: Update the JAVA_HOME environment variable
lineinfile:
path: ~/.bashrc
regexp: "^export JAVA_HOME="
line: "export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64"
state: present
This Ansible Playbook will update the JAVA_HOME
environment variable in the .bashrc
file on all the hosts defined in the inventory.
Updating Cron Jobs
Ansible can also be used to manage cron jobs on remote hosts. You can use the cron
module to create, update, or delete cron jobs.
Here's an example of using Ansible to update a cron job that runs a backup script every day at 2:00 AM:
- hosts: all
tasks:
- name: Update the backup cron job
cron:
name: Backup script
minute: 0
hour: 2
job: /opt/scripts/backup.sh
state: present
This Ansible Playbook will update the cron job on all the hosts defined in the inventory, ensuring that the backup script is run every day at 2:00 AM.
These are just a few examples of the practical use cases for updating file content on remote hosts using Ansible. The flexibility and power of Ansible make it a valuable tool for automating a wide range of IT tasks, from configuration management to application deployment and beyond.