Ansible Contd
- Manual Steps:
sudo apt update
sudo apt install apache2 -y
sudo apt install php libapache2-mod-php php-mysql -y
# Create a file in /var/www/html/info.php "<?php phpinfo(); ?>"
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
sudo service apache2 restart
- We have written the play book for the following steps
sudo apt update
sudo apt install apache2 -y
- Now lets try to use the ansible module for this manual step
sudo apt install php libapache2-mod-php php-mysql -y
- Refer Here for the changes done
- Lets do syntax check

- Now lets apply changes

- Now we need to create a file using ansible. Manual steps
# Create a file in /var/www/html/info.php "<?php phpinfo(); ?>"
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
- To create empty files we have file module but to create files with pre-existing content we have either copy the files from ansible control node to nodes or create a file from content using copy module Refer Here
- Refer Here for the changes

- Now we need to restart the apache service. Manual steps
sudo service apache2 restart
- Refer Here for the service module. Lets enable the apache2 service to start automatically during system restarts and ensure the service is restarted after php info page creation.
- Refer Here for the changes done

- Lets try to rerun the playbook

- Ideally we would like to restart apache only when info.php is created.
- We need to execute
Restart Apache2Task only whencreate info.phptask is executed. - In ansible when we want to execute some tasks as a reaction to other tasks we need to use handlers.
- Refer Here for the changeset containing restarting the service as handler

- Refer Here for handler documentation
- We need to execute
- The playbook which we have written
---
- name: Install apache and php
hosts: all
become: yes
tasks:
- name: install apache2
apt:
name: apache2
update_cache: yes
state: present
- name: install php modules
apt:
name:
- php
- libapache2-mod-php
- php-mysql
state: present
- name: create info.php
copy:
dest: /var/www/html/info.php
content: |
<?php
phpinfo();
?>
notify:
- Restart Apache2
handlers:
- name: Restart Apache2
service:
name: apache2
enabled: yes
state: restarted
-
To be effective in playbook development, we should
- install softwares/deploy applications manually to know the steps
- Become good in searching right ansible modules
- Good with YAML understanding
-
Exercise:
- Try to install the following applications manually on any linux machine
- Tomcat
- Nginx
- mysql
- Postgres
- Mongo db
- Try to install the following applications manually on any linux machine
