Yukta chakravarty

Dec 25, 2020

2 min read

Giving idempotance to restart HTTPD service

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 }}

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
— 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”
— name: “Installing httpd”
name: “httpd”
— name: “Creating customized document root”
state: directory
path: “{{ doc_root }}”
— name: “Copying file to document root”
dest: “{{ doc_root }}/authweb.html”
content: “Welcome to my customized and authenticated web page!!”
— name: “copying cust.conf file”
dest: “/etc/httpd/conf.d/cust.conf”
src: “cust.conf”
notify: webserver

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

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