How to make HTTPD service Idempotence in nature with ansible !!
We all know fact that ansible modules are by default idempotent in nature. which means without making changes in configuration files whenever we execute playbook services will get restarted. ansible has this by default nature. but some modules in ansible has not support this nature or for some services proper modules are not available so at that time we have to take help of built in modules to execute service.
as example if we take HTTPD service a simple ansible playbook for this will be
hosts: webvars_files: variables.ymltasks:
- name: "download package and install service"
package:
name: httpd
state: present- name: "copy content to index.html file"
copy:
content: "This is ansible test file"
dest: "{{ document_root }}/index.html"- copy:
dest: "{{ document_root }}/index.html"
src: "index.html"- template:
dest: "/etc/httpd/conf.d/my.conf"
src: "httpd.conf"- name: "start service"
service:
name: httpd
state: started
- firewalld:
port: "{{ port }}/tcp"
state: enabled
permanent: yes
immediate: yes
This will be simple ansible setup.yml file which first install package then copy content “This is ansible test file” to index.html some configuration we done on httpd.conf file and then start service and setup firewalld rule for port 80/tcp .
but after each run of playbook service always get started which is not good for resources so for resource management and achieving idempotency we can use register key word and make decision with some changes, or we can use notify and handler method for this
handlers like a function which we can use anywhere in code by notify keyword code for this is shown below
hosts: webvars_files: variables.yml tasks:
- name: "download package and install service"
package:
name: httpd
state: present- name: "copy content to index.html file"
copy:
content: "This is ansible test file"
dest: "{{ document_root }}/index.html"- copy:
dest: "{{ document_root }}/index.html"
src: "index.html"- template:
dest: "/etc/httpd/conf.d/my.conf"
src: "httpd.conf"
notify:
- Restart httpd
- firewalld:
port: "{{ port }}/tcp"
state: enabled
permanent: yes
immediate: yeshandlers:
- name: Restart httpd
service:
name: "httpd"
state: "started"
enabled: yes
before making changes in file output
after making changes by changing port the output is
Thanks for reading story!
I hope you will definitely like it!
GitHub link : https://github.com/Yash202000/ARTH-TASKS/tree/main/Task%2011/task%2011.3