Ansible URI Module Tutorial: Real-World Application Health Checks, REST API Validation and DevOps Automation

Hello DevSecOps and Automation Engineers!

Welcome back to the DevOps Hunter blog.

One of the most common requirements in enterprise automation is validating whether an application is actually available after a deployment, patching activity, server reboot, or service restart.

Simply starting a service does not guarantee that the application is ready to serve users. This is where the Ansible uri module becomes one of the most powerful tools in a DevOps engineer's toolkit.

In this hands-on tutorial, we will explore the Ansible URI module, understand its key parameters, and work through several real-world examples that are commonly used in production automation workflows.

Production Health Check workflow using URI module


What You'll Learn

By the end of this article, you will be able to:

  • Understand the purpose of the Ansible URI module
  • Perform HTTP and HTTPS application health checks
  • Validate application response codes
  • Test REST API endpoints
  • Handle multiple acceptable HTTP status codes
  • Retrieve and process API response content
  • Parse JSON responses
  • Authenticate against secured endpoints
  • Build reliable post-deployment validation workflows

Web Application returns status HTTPCode 200 for success, 404 for failures, and also for 503 for Server internal issues. When you work on the restart of a web application we need to know the status of the application to proceed with the next move. So this uri module is most important for reboot and restart of web applications using ansible.


Why Use the Ansible URI Module?

Modern applications communicate primarily through HTTP and HTTPS endpoints.

When performing automation activities such as:

  • Application deployments
  • Service restarts
  • Operating system patching
  • Load balancer maintenance
  • Disaster recovery testing
  • CI/CD pipeline validation

you must verify whether the application is actually responding correctly before moving to the next step.

A healthy application may return:

HTTP CodeMeaning
200Success
201Resource Created
301Redirect
302Temporary Redirect

An unhealthy application may return:

HTTP CodeMeaning
404Page Not Found
500Internal Server Error
502Bad Gateway
503Service Unavailable

The Ansible uri module enables automation engineers to validate these responses programmatically and make intelligent decisions within their playbooks.

Commonly used uri module parameters

he URI module supports many parameters for interacting with web applications and APIs.

Some of the most frequently used parameters include:

ParameterPurpose
urlTarget URL
methodHTTP Method
status_codeExpected Response Code
headersAdd Custom Headers
bodyRequest Payload
body_formatJSON or Raw Format
return_contentReturn Response Content
userUsername for Authentication
passwordPassword for Authentication
timeoutRequest Timeout
validate_certsSSL Certificate Validation
follow_redirectsHandle Redirect Responses

method - REST api possible methods it will supports GET POST DELETE PUT HEAD PATCH TRACE 

Prerequisites

Before starting:

  • Ansible installed
  • Linux control node
  • Network connectivity
  • Web application or API endpoint to test

For demonstration purposes, we'll use:

  • https://devopshunter.blogspot.com
  • https://httpbin.org

  • These public services make it easy to experiment safely.

    Use Case 1: Verify Website Availability

    One of the simplest and most common use cases is verifying whether a website is accessible. Let's check out blog URL does the Ansible uri module can test?

    - name: Check public domain URL
      hosts: localhost
      gather_facts: no
      tasks:
      - name: uri
        uri:
          url: https://devopshunter.blogspot.com
          method: GET
          validate_certs: False
    
    Execute the playbook as
    ansible-playbook urlcheck.yml

    Ansible uri module with GET method

    Why This Matters

    This validation is commonly used:

    • After application deployments
    • During monitoring checks
    • For synthetic transaction testing
    • During disaster recovery exercises

    Use Case 2: Validate Application Status Code

    Many enterprise applications expose health-check URLs.

    Instead of simply checking connectivity, validate the actual HTTP response code. Now we can test our project related application URLs with the following playbook

    - name: test apache url
      hosts: web
      gather_facts: no
      tasks:
      - name: uri
        uri:
          url: http://{{ansible_host}}
          method: GET
          validate_certs: False
          status_code: 200
    
    Testing the above web application testing test run as follows:
    Image
    
    

    Ansible uri module with GET method and status_code checking
    Ansible uri module with GET method and status_code checking

    Why This Matters

    If the application returns anything other than HTTP 200, the playbook fails immediately.

    This prevents downstream automation from executing against an unhealthy application.


    Use Case 3: Accept Multiple Valid Status Codes

    Certain applications legitimately return different response codes.

    Examples:

    • 200 OK
    • 201 Created
    • 301 Redirect
    - name: Check status code public domain URL
      hosts: localhost
      gather_facts: no
      tasks:
        - name: Check uri in 200,201,301
          uri:
            url: https://httpbin.org/status/500
            method: POST
            status_code: [200,201,301]
            validate_certs: False
    
    Execute the play and check what does 
    ansible-playbook uri_multi_status_code.yml

    Image: 

    Ansible uri module check for multiple HTTP codes
    Ansible uri module multiple status code

    Production Tip

    Load balancers, reverse proxies, and web gateways often return redirects. Accepting multiple valid response codes helps avoid false-positive failures.


    Use Case 4: Retrieve Response Content

    Sometimes checking the status code is not enough. You may need to inspect the actual response body.


    - name: Check content
      hosts: db
      gather_facts: no
      tasks:
      - name: Show content of a given uri
        uri:
          url: http://httpbin.org/get
          return_content: yes
          method: GET
        register: __content
    
      - name: debug
        debug:
          var: __content.content
    
    
    Execute play as follows:
    ansible-playbook check_content.yml
    Image
    Ansible uri module content
    Content of given url usibng ansible uri module

    Useful when:

    • Verifying API payloads
    • Checking application versions
    • Validating deployment metadata
    • Troubleshooting unexpected responses

    Use Case 5: Parse JSON Responses

    Modern REST APIs typically return JSON data.

    The URI module automatically converts JSON responses into structured objects.

    # Filename uri_body.yml
    - name: Get the body of the url
      hosts: db
      gather_facts: false
      tasks:
      - name: Get the status, url from body from uri
        uri:
          url: http://httpbin.org/get
          method: GET
          return_content: yes
          validate_certs: False
          body_format: json
        register: __body
      - name: debug status, url
        debug:
          var: __body.status, __body.json.url
      - name: debug json block
        debug:
          var: __body.json
    
    Execute play as follows:
    ansible-playbook uri_body.yml
    Note that URL passed here is the test URL, whereas in projects we need to pass this value of web applications that provide the REST service that can be used with the HTTP Get request object.

    Ansible uri module body parameter
    Ansible uri module example to get body parameter

    Researcher's Corner

    One of the best ways to understand unfamiliar APIs is by:

    1. Calling the endpoint with the URI module.
    2. Registering the output.
    3. Exploring the returned JSON structure.
    4. Extracting only the fields you need.

    This approach dramatically accelerates API integration projects.


    Use Case 6: Basic Authentication

    Many internal applications and REST APIs require authentication.

    The URI module supports Basic Authentication using username and password credentials.


    # File: uri_basic_auth.yml
    - name: Get the body of the url
      hosts: localhost
      gather_facts: false
      tasks:
      - name: uri module using user password
        uri:
          url: https://httpbin.org/basic-auth/vybhava/technologies
          user: "vybhava"
          password: "technologies"
          method: GET
          validate_certs: False  
      
    Execution
    ansible-playbook uri_basic_auth.yml

    Ansible uri basic auth
    Ansible uri module basic auth parameters user, password

    Real-World Applications

    Basic Authentication is commonly used for:

    • Internal APIs
    • Legacy web applications
    • Monitoring systems
    • Infrastructure management platforms
    interesting facts:

    Basic auth testing on browser 



    Reader Challenge

    Now it's your turn.

    Try implementing the following tasks:

    1. Validate the availability of a public website using the GET method.
    2. Check a web application's health endpoint and fail the playbook if it does not return HTTP 200.
    3. Configure a task that accepts multiple valid HTTP response codes.
    4. Retrieve and display API response content.
    5. Parse a JSON response and extract specific fields.
    6. Authenticate against a Basic Authentication endpoint.
    7. Create an Ansible role that performs application health checks after service restarts.
    8. Build a playbook that validates multiple application URLs and generates a health report.

    Bonus Challenge

    Design a deployment validation workflow that:

    • Restarts an application
    • Waits for service readiness
    • Performs URI validation
    • Verifies application health
    • Generates a success or failure notification

    This closely resembles real-world DevOps and DevSecOps automation pipelines.

    Have fun and enjoy experimenting with this uri module.

    What Is Your Favorite URI Module Use Case?

    Do you use the URI module for:

    • Application health checks?
    • API testing?
    • Deployment validation?
    • Load balancer verification?
    • Self-healing automation?

    Share your most interesting URI module use case in the comments. Your experience may help another engineer solve a production challenge.

    Good references on the get_url module
     

    Comments

    Popular Articles

    DevOps Weapons

    Ansible Jinja2 Templates: A Complete Guide with Examples