Restarting httpd Service in idempotence nature

Ankit Pramanik
2 min readDec 9, 2020

--

Idempotence: Idempotence means that applying an operation once or applying it multiple times has the same effect. Examples: Multiplication by zero. No matter how many times you do it, the result is still zero.

When we make any changes to configuration files then only we restart any service. If we are executing a command to restart the service it will consume compute resources.

When we run ansible-playbook for restarting the service of httpd. It will again restart the service at the target node but we want the service to only restart when we make any change to configuration files otherwise it will not restart the service of httpd and save the compute resources.

notify

List of handlers to notify when the task returns a ‘changed=True’ status.

handlers module in ansible

Sometimes we want a task to run only when a change is made on a machine. For example, We may want to restart a service if a task updates the configuration of that service, but not if the configuration is unchanged. Ansible uses handlers to address this use case. Handlers are tasks that only run when notified.

Here is the complete playbook for the following:

- hosts: all  vars_files:
- http_var.yml
#vars_prompt:
#- name: dvd_dir
# private: no
# vars:
# - dvd_dir: "/dvd1"
# - docroot: "/var/www/lw"
# - http_port: 8080
tasks:
- file:
state: directory
path: "{{ dvd_dir }}"
- name: "mounting dvd"
mount:
src: "/dev/cdrom"
path: "{{ dvd_dir }}"
state: mounted
fstype: "iso9660"
- name: "Setting yum repo"
yum_repository:
baseurl: "{{ dvd_dir}}/AppStream"
name: "mydvd1"
description: "yum1"
gpgcheck: no
- name: "setting 2nd yum repo"
yum_repository:
baseurl: "{{ dvd_dir }}/BaseOS"
name: "mydvd2"
description: "yum2"
gpgcheck: no
- name: "installing httpd"
package:
name: "httpd"
state: present
- name: "creating lw directory inside /var/www/"
file:
state: directory
path: "{{ docroot }}"
- template:
dest: "/etc/httpd/conf.d/lw.conf"
src: "lw.conf"
notify:
- Restart httpd
- copy:
dest: "{{ docroot }}/index.html"
content: "this website has been configures using Ansible"
- name: "restarting the httpd service"
service:
name: "httpd"
state: restarted
enabled: yes
- name: "Setting up Firewall on port: {{ http_port }}"
firewalld:
port: "{{ http_port }}/tcp"
state: enabled
permanent: yes
immediate: yes
- handlers:
- name: Restart httpd
service:
name: "httpd"
state: started
enabled: yes

Attaching the variables file:

dvd_dir: "/dvd1"
docroot: "/var/www/html"
http_port: 8080

Attaching the configuration file:

Listen {{ http_port }}<VirtualHost {{ ansible_facts['default_ipv4']['address'] }}:{{ http_port }}>
DocumentRoot {{ docroot }}
</VirtualHost>

Github Repository: https://github.com/ankit98040/Ansible_playbooks

Thank You for reading.

--

--