HTTPD SERVER | ANSIBLE | MANAGING STATE OF HTTPD | CHANGED_WHEN
The problem that we are going to solve is restarting HTTPD Service is not idempotence in nature and also consume more resources suggest a way to rectify this challenge in Ansible playbook.
I made a Play-book that configures the HTTPd server on a RedHat system
This code will show CHANGED (YELLOW ) color even if it's not.
- hosts: all
vars_prompt:
- name: dvd_dir
private: no
prompt: "enter dvd mount point"
tasks:
- file:
state: directory
path: "{{ dvd_dir }}"
- mount:
src: "/dev/cdrom"
path: "{{ dvd_dir }}"
state: mounted
fstype: "iso9660"
- yum_repository:
baseurl: "{{ dvd_dir }}/AppStream"
name: "mydvd1"
description: "my dvd1 for pakage"
gpgcheck: no
- yum_repository:
baseurl: "{{ dvd_dir }}/BaseOS"
name: "mydvd2"
description: "my dvd2 for pakage"
gpgcheck: no
- package:
name: "httpd"
state: present
- file:
state: directory
path: "/var/www/suyog"
- copy:
src: "/root/ansible/playbook/new.conf"
dest: "/etc/httpd/conf.d/new.conf"
- copy:
dest: "/var/www/suyog/index.html"
content: "This is my web site\n"
- name: "Restarting httpd Service"
shell: "/usr/sbin/httpd"
- firewalld:
port: "8080/tcp"
state: enabled
permanent: yes
immediate: yes
The Httpd Server is already running on the target node
Then also when running ansible-playbook it will say changed (YELLO) but it should be GREEN
Here comes the play of changed_when to explicitly tell ansible when to consider the task as Successful or changed.
What is Changed_when?
These modules give us a way to make ansible do something when a certain condition is met or satisfied
- Just adding changed_when and a debug message to display the startoutput
- name: "Restarting httpd service"
shell: "/usr/sbin/httpd"
register: startoutput
changed_when: "'already running' not in startoutput.stdout"
- debug:
msg: "{{startoutput.stdout}}"
- After changing the above code we get the needed output
The color is Not changed(GREEN) this time and not YELLOW(Changed)
In other words, It is unchanged
HOPE YOU GET IT
Keep Learning !! Keep Sharing
Thank you for visiting.
🤩🤩
Good job Suyog Shinde ✨✌🏻
Great Suyog Shinde