handling error codes

63 views
Skip to first unread message

Veera

unread,
Jul 31, 2023, 7:56:11 AM7/31/23
to Ansible Project
Hi ,

I have a playbook  with the  below lines .

$ cat double_check.yml
---
- name: playbook to test the status of the web
  hosts: centos8-latest
  tasks:
    - block:
        - name: Install the  httpd packages
          ansible.builtin.yum:
            name: httpd
            state: latest

        - name: Enable and Start the httpd service
          ansible.builtin.service:
            name: httpd
            state: started
            enabled: true

        - name: Check web site from web server
          ansible.builtin.uri:
            url: http://{{ ansible_fqdn }}
            return_content: true
            status_code: 200
          register: example_webpage
          failed_when: example_webpage.status != 200



      rescue:
        - name: Restart web server
          ansible.builtin.service:
            name: httpd
            state: restarted

#we still can have handlers to  demo this playbook  

This Playbook works as expected  until  the status code is 200.
[user@centos8-latest html]$ ls -l
total 4
-rw-r--r-- 1 root root 104 Jul 28 10:36 index.html
[user@centos8-latest html]#


If there is no index.html , CentOS/redhat  shows its  apache foundation page which is returning a different  status code[409 ] . which is causing the task to fail .

I am expecting  the Status Code 200  [success] ,  409[already running] and 404/others[failed]
How can we handle this error?  Ignore_error=yes  is not required.
If  Status Code = 200 , then no change required . ( a handler to be called  after that )
if status code=409 , it should pass and still continue to next task (if added). (no handler to be called  )
other codes/404 can fail.


Is there an option to declare "status code =200 or 409 "in the single line?
Or we have to  handle them with 2 different play ? possible ?





Todd Lewis

unread,
Jul 31, 2023, 8:13:04 AM7/31/23
to ansible...@googlegroups.com, uto...@gmail.com
status_code takes a list. The default is [200], but you can say
status_code:
  - 200
  - 409
Cheers,
--
Todd

Veera

unread,
Jul 31, 2023, 11:53:35 AM7/31/23
to Ansible Project
Thanks Todd,  

It worked and  Yes I  could have referred the doc status_code  in depth  . 
Reply all
Reply to author
Forward
0 new messages