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

Skabhi
3 min readJul 4, 2021

What is idempotency in ansible?

Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. This principle enables Ansible to be declarative and yet reliable is idempotence, a concept borrowed from mathematics.

Initially, Apache is not idempotent in nature. This makes apache use more memory and resources every time we run the ansible playbook to configure our web server on the managed node. Because every time we run the ansible playbook it will run the whole process from scratch as it is making it “non-idempotent’’. We can make apache idempotent by using handlers in our ansible playbook in the following manner.

What are Handlers in ansible?

Sometimes you want a task to run only when a change is made on a machine. For example, you 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.

Let’s look into playbook code:-

- hosts: localhost
vars:
doc_root : /var/www/abhi
httpd_port: 8081
tasks:
- name: Installing Webserver
yum:
name:
- httpd
- name: Create coustom doc root
file:
path: "{{ doc_root }}"
state: directory
- name: Copy Coustom conf file
template:
dest: "/etc/httpd/conf.d/web.conf"
src: web.conf
notify: restart httpd
- name: Copy the webpage code to doc root
copy:
src: index.html
dest: "{{ doc_root }}/index.html"
- name: Start the firewall and enabled
service:
name: firewalld
state: started
- name: firewalld permits access to httpd service port
firewalld:
port: "{{ httpd_port }}/tcp"
permanent: yes
state: enabled
immediate: yes
- name: Start and enable services
service:
name: httpd
state: started
enabled: yes
handlers:
- name: restart httpd
service:
name: httpd
state: restarted

web.conf

Listen {{ httpd_port }} 
<VirtualHost {{ ansible_facts['default_ipv4']['address']}}:{{httpd_port}}>
DocumentRoot {{ doc_root }}
</Virtualhost>

index.html

<h1>This is test page created by ansible</h1>

Now, Run the playbook

Finally Playbook successfully executed, you can see webserver .

That’s all for this article. Thanks For Reading😊

--

--