Ansible URI Module Explained with Examples

Ansible uri Module Example

The Ansible URI module is a powerful tool for interacting with HTTP and REST APIs. It allows you to send HTTP requests and handle responses directly from your playbooks, making it an essential module for managing web services and APIs.

This article will delve deep into the Ansible URI module with examples.

Introduction to the Ansible URI Module

The URI module in Ansible sends HTTP requests to a given URL and retrieves the responses. It supports a wide range of HTTP methods such as GET, POST, PUT, DELETE, and more. This makes it highly versatile for tasks like:

  • Validating the availability of a web service.
  • Automating REST API calls.
  • Managing remote resources programmatically.

The module can handle authentication, manage headers, and work with JSON payloads, making it ideal for working with RESTful APIs.

Basic Syntax

Here is the basic syntax:

- name: Example of Ansible URI Module
  ansible.builtin.uri:
    url: URL
    method: HTTP_METHOD
    headers: HTTP_HEADERS
    body: REQUEST_BODY
    status_code: EXPECTED_STATUS_CODES
    return_content: BOOLEAN
  register: OUTPUT_VARIABLE

Key Parameters:

  • url: The target URL for the request.
  • method: The HTTP method (GET, POST, PUT, etc.).
  • headers: Additional headers to include in the request.
  • body: Data to send with the request, typically in JSON format.
  • status_code: List of acceptable HTTP status codes.
  • return_content: If set to true, returns the response body.

Example 1: Checking the Status of a Web Service

This example checks if a web service is running by sending a GET request.

- name: Verify the status of a web service
  hosts: webservers
  tasks:
    - name: Send GET request to check if the web service is running
      ansible.builtin.uri:
        url: "http://example.com/health"
        method: GET
        status_code: 200
        return_content: yes
      register: response

    - name: Validate the response content for specific keywords
      debug:
        msg: >
          The web service returned the following response:
          {{ response.content }}

    - name: Ensure the response contains 'healthy'
      fail:
        msg: "The web service is not healthy!"
      when: "'healthy' not in response.content"

In this example:

  • GET Request: Checks the service availability.
  • Validate Content: Inspect the response for keywords like healthy using the debug module.
  • Fail Condition: Halts execution if the response does not contain the expected string using the when condition.

Example 2: Making a POST Request

Here, we send a POST request with a JSON payload.

- name: Create a resource using API
  hosts: webservers
  tasks:
    - name: Send POST request to create a resource
      ansible.builtin.uri:
        url: "http://example.com/api/resource"
        method: POST
        headers:
          Content-Type: "application/json"
        body: '{"name": "New Resource", "type": "example"}'
        status_code: 201
        return_content: yes
      register: create_response

    - name: Display the creation response
      debug:
        var: create_response.json

This playbook sends a POST request to an API to create a resource, verifies the success with a 201 status code, and displays the API response content.

Example 3: Handling Authentication

Many APIs require authentication. Here’s an example using a basic authentication header.

- name: Fetch data from an API with authentication
  hosts: webservers
  tasks:
    - name: Send GET request with Bearer token
      ansible.builtin.uri:
        url: "http://example.com/api/protected"
        method: GET
        headers:
          Authorization: "Bearer {{ token }}"
        status_code: 200
        return_content: yes
      register: auth_response

    - name: Display the authenticated API response
      debug:
        var: auth_response.json

This playbook retrieves data from a protected API using a Bearer token for authentication and displays the API response content.

Example 4: Working with Headers and JSON Payloads

In this example, we retrieve specific data from a web service by sending custom headers.

- name: Fetch data with custom headers
  hosts: webservers
  tasks:
    - name: Send GET request with custom headers
      ansible.builtin.uri:
        url: "http://example.com/api/data"
        method: GET
        headers:
          Accept: "application/json"
          User-Agent: "Ansible-URI-Example"
        status_code: 200
        return_content: yes
      register: data_response

    - name: Display fetched data
      debug:
        var: data_response.json

This example fetches data from an API using custom headers and displays the JSON response content.

Example 5: Handling Non-200 Status Codes

The URI module provides mechanisms to handle errors gracefully:

- name: Handle non-200 status codes
  hosts: webservers
  tasks:
    - name: Send GET request to a non-existing resource
      ansible.builtin.uri:
        url: "http://example.com/api/unknown"
        method: GET
        status_code:
          - 200
          - 404
        return_content: yes
      register: error_response

    - name: Display message if the resource is missing
      debug:
        msg: "Resource not found!"
      when: error_response.status == 404

This playbook sends a GET request to handle both successful (200) and missing resource (404) responses, displaying a specific message if the resource is not found.

Conclusion

The Ansible URI module is an essential tool for interacting with web services and APIs directly from your playbooks. It supports a wide range of HTTP methods, headers, and authentication mechanisms, enabling seamless automation of API-driven tasks.

FAQs

1. Can I save the response data from the URI module?

Yes, you can save the response content using the return_content parameter and write it to a file.

2. Can I use the URI module to delete resources via an API?

Yes, use the DELETE method in the method parameter to delete resources.

3. Can I use the URI module for non-API HTTP requests?

Yes, the module can handle any HTTP or HTTPS requests, not just API calls.

About Hitesh Jethva

I am Hitesh Jethva, Founder and Author at Code2DevOps.com. With over 15 years of experience in DevOps and open source technologies, I am passionate about empowering teams through automation, continuous integration, and scalable solutions.

View all posts by Hitesh Jethva