Giving idempotance to restart HTTPD service

Yukta chakravarty
2 min readDec 25, 2020

Task Description:

Restarting HTTPD Service is not idempotence in nature and also consume more resources suggest a way to rectify this challenge in Ansible playbook

What is idempotance in Ansible ?

In Ansible when a task such as when installing a package if package is already installed ansible checks first whether it is already present and installs the package only if package is not installed , this is called as idempotance

Why restart httpd service ?

Whenever we make changes in configuration file of httpd we need to restart the server for the changes to apply. We want to restart httpd service only when there is change in configuration file , we don’t want to restart it otherwise

In service module when we use state=restarted , it will always restart the server irrespective of any condition.

The configuration file for customized document root and port no has following contents:

Listen {{ port_no }}
<VirtualHost {{ ansible_facts[“default_ipv4”][“address”] }}:{{ port_no }} >
DocumentRoot {{ doc_root }}
</VirtualHost>

This file is to be copied at this location /etc/httpd/conf.d/

We use handlers to restart service , we use notify keyword to notify only when the output of a task is changed and the handler runs the task

You can find the code to create customized web server with authentication:

- hosts: all
vars_prompt:
— name: username
private: no
prompt: “Enter user name”
— name: pas
prompt: “Password for user”
— name: doc_root
private: no
prompt: “Enter document root”
— name: port_no
private: no
prompt: “Enter port number to host”
tasks:
— name: “Installing httpd”
package:
name: “httpd”
— name: “Creating customized document root”
file:
state: directory
path: “{{ doc_root }}”
— name: “Copying file to document root”
copy:
dest: “{{ doc_root }}/authweb.html”
content: “Welcome to my customized and authenticated web page!!”
— name: “copying cust.conf file”
template:
dest: “/etc/httpd/conf.d/cust.conf”
src: “cust.conf”
notify: webserver

- name: “configure httpd.conf file”
replace:
path: “/etc/httpd/conf/httpd.conf”
regexp: “AllowOverride None”
replace: “AllowOverride AuthConfig”
— name: “copying .htaccess file”
copy:
dest: “{{ doc_root }}/.htaccess”
src: “.htaccess”
— name: “Installing python36 package”
package:
name: “python36”
state: present
— pip:
name: “passlib”
— name: “Adding user and password”
htpasswd:
path: “/etc/web.passwd”
name: “{{ username }}”
password: “{{ pas }}”
— name: “Allowing tcp”
firewalld:
port: “8080/tcp”
state: enabled
permanent: yes
immediate: yes


handlers:
— name: “webserver”
service:
name: “httpd”
state: restarted

--

--