The ability to interact with a Kubernetes cluster is not limited to the deployment of manifests or the modification of resource states. A critical component of professional cluster management is the ability to read the current state of the cluster, conduct comprehensive audits of configurations, and feed real-time resource information into downstream automation tasks. Within the Ansible ecosystem, this capability is centralized in the kubernetes.core.k8s_info module. This module serves as a sophisticated bridge between the Ansible automation engine and the Kubernetes API, allowing operators to query the cluster and receive structured data. Unlike modules designed to ensure a certain state (declarative), k8s_info is an information-gathering tool (imperative/query) that enables the creation of intelligent playbooks capable of responding to the actual state of the environment rather than blindly applying changes.
Technical Foundations and Prerequisites
To successfully implement the kubernetes.core.k8s_info module, specific environmental requirements must be met to ensure the communication channel between the Ansible control node and the Kubernetes API server is secure and functional.
The primary requirement is the installation of Ansible version 2.12 or higher. The transition to version 2.12 marked a significant shift in how collections are handled, and the kubernetes.core collection relies on this architecture for stability and feature parity. The installation of the collection is performed via the Ansible Galaxy CLI.
ansible-galaxy collection install kubernetes.core
In addition to the collection, the underlying Python environment must have the kubernetes Python library installed. This library acts as the official client for the Kubernetes API, handling the HTTP requests and response parsing that the k8s_info module utilizes.
pip install kubernetes
Beyond the software dependencies, a valid kubeconfig file must be present. The kubeconfig contains the necessary credentials (certificates, tokens, or usernames) and the API server endpoint address required to authenticate requests. Without a properly configured kubeconfig, the module will fail to establish a connection to the cluster, resulting in authentication or connection timeout errors.
Comprehensive Analysis of Module Parameters
The kubernetes.core.k8s_info module provides a granular set of parameters that allow users to narrow down the scope of their queries, which is essential for performance and precision in large-scale clusters.
The following table outlines the core parameters used to define the scope of a Kubernetes API query.
| Parameter | Description | Technical Detail |
|---|---|---|
kind |
Resource Type | Defines the type of object to query (e.g., Pod, Deployment, Service, Namespace). |
api_version |
API Group/Version | Specifies the API version of the resource (e.g., apps/v1 for Deployments, v1 for Pods). |
name |
Resource Identifier | Allows for a specific query of a single resource by its unique name. |
namespace |
Isolation Scope | Limits the search to a specific namespace. If omitted, the query can be cluster-scoped or target all namespaces. |
label_selectors |
Label Filter | A list of strings used to filter resources based on their metadata labels. |
field_selectors |
Field Filter | A list of strings used to filter resources by specific fields. |
The field_selectors parameter is particularly powerful as it leverages the native Kubernetes API filtering capabilities. Supported field selectors include metadata.name, metadata.namespace, status.phase (specifically for pods), and spec.nodeName. By using these selectors, the filtering happens on the server side (the Kubernetes API server), which significantly reduces the amount of data transferred over the network compared to filtering the results using Jinja2 on the Ansible side.
Querying Strategies and Resource Retrieval
There are multiple patterns for retrieving information depending on whether the goal is to inspect a single object or audit a collection of objects.
Direct Query by Name
When the exact name of a resource is known, the most efficient method is to query by name and namespace. This returns a targeted result set. However, a critical technical detail of the k8s_info module is that the resources field in the returned data is always a list, regardless of whether a single resource was found or multiple resources were returned.
Example implementation for retrieving a specific deployment:
yaml
- name: Get deployment details
kubernetes.core.k8s_info:
kind: Deployment
name: web-api
namespace: production
register: deploy_info
To access the data from this result, the user must reference the first element of the list (resources[0]). This structure ensures consistency in how the module handles data, but it requires the user to implement checks to verify if the list is not empty before attempting to access specific attributes.
Handling Missing Resources
A robust playbook must account for the possibility that a requested resource does not exist. Failure to do so will result in an "index out of range" error when attempting to access resources[0].
Example of a safe extraction pattern:
```yaml
- name: Show the full resource
ansible.builtin.debug:
var: result.resources[0]
when: result.resources | length > 0
- name: Handle missing resource
ansible.builtin.debug:
msg: "Resource not found"
when: result.resources | length == 0
```
Advanced Data Processing with Jinja2
The true utility of the k8s_info module is realized when its output is processed using Jinja2 filters. Because the module returns structured JSON data, users can transform, filter, and map this data to drive complex logic.
Mapping and Attribute Extraction
When querying all resources of a certain kind within a namespace, the result is a large list of objects. To extract only specific pieces of information, such as the names of all deployments, the map filter is employed.
yaml
- name: Extract just the names
ansible.builtin.set_fact:
deploy_names: "{{ all_deploys.resources | map(attribute='metadata.name') | list }}"
Complex Filtering for Health Audits
To identify degraded resources, such as deployments where the number of ready replicas is less than the desired number of replicas, users can combine selectattr and json_query.
yaml
- name: Find deployments with fewer ready replicas than desired
ansible.builtin.set_fact:
degraded_deploys: "{{ all_deploys.resources | selectattr('status.readyReplicas', 'defined') | rejectattr('status.readyReplicas', 'equalto', none) | list | json_query('[?status.readyReplicas < spec.replicas]') }}"
This process involves three layers of filtering:
1. Ensuring the status.readyReplicas field exists.
2. Rejecting any entries where the field is null.
3. Using a JSONPath query to compare the current ready state against the desired specification.
Image Registry Auditing
For security and compliance, it is often necessary to audit which container images are running across the cluster. This requires flattening the nested structure of the Kubernetes resource.
yaml
- name: Extract container images from all deployments
ansible.builtin.set_fact:
all_images: "{{ all_deploys.resources | map(attribute='spec.template.spec.containers') | flatten | map(attribute='image') | unique | sort | list }}"
In this sequence, the map attribute extracts the list of containers, flatten converts the list of lists into a single list of container objects, and a second map extracts the image string. The unique and sort filters then ensure a clean, non-redundant list of all images used in the production namespace.
Real-World Implementation Patterns
The k8s_info module can be integrated into various operational workflows to create "intelligent" playbooks.
External Service Discovery
One common use case is identifying all services of type LoadBalancer to map external entry points into the cluster.
```yaml
- name: Find services of type LoadBalancer
kubernetes.core.k8sinfo:
kind: Service
register: allservices
- name: List external services
ansible.builtin.debug:
msg: "External: {{ item.metadata.namespace }}/{{ item.metadata.name }} ({{ item.spec.type }})"
loop: "{{ allservices.resources | selectattr('spec.type', 'equalto', 'LoadBalancer') | list }}"
loopcontrol:
label: "{{ item.metadata.name }}"
```
Resource Detail Extraction
For detailed reporting, the module allows the extraction of specific metadata and status fields into a readable format.
yaml
- name: Display deployment status
ansible.builtin.debug:
msg:
name: "{{ deploy_info.resources[0].metadata.name }}"
replicas: "{{ deploy_info.resources[0].spec.replicas }}"
ready: "{{ deploy_info.resources[0].status.readyReplicas | default(0) }}"
image: "{{ deploy_info.resources[0].spec.template.spec.containers[0].image }}"
created: "{{ deploy_info.resources[0].metadata.creationTimestamp }}"
Troubleshooting Compatibility and Installation Failures
Issues often arise when attempting to use k8s_info in legacy environments or disconnected nodes. A documented case involves the attempt to use the module in Ansible version 2.9 on CentOS 7.9 with Python 3.6.
The "Exception Occurred During Task Execution" Error
Users attempting to manually install collections by untarring them into directories such as /home/sac/.ansible/collections/ansible_collections/kubernetes/core on older versions of Ansible (like 2.9.27) have reported generic exceptions during task execution.
The root cause of these failures typically stems from:
- Version Incompatibility: The kubernetes.core collection is designed for ansible-core 2.12+. Using it with 2.9 leads to API mismatches within the Ansible engine.
- Dependency Gaps: Manual installation of the collection via tar does not resolve the Python dependencies (the kubernetes library), which must be installed via pip.
- Pathing Issues: Manually creating directories for collections without using ansible-galaxy can lead to incorrect metadata indexing, preventing the module from being discovered correctly.
For users on older systems, the recommendation is to upgrade to Ansible 2.12+ to ensure full compatibility with the kubernetes.core collection and to use ansible-galaxy for installation rather than manual directory manipulation.
Conclusion
The kubernetes.core.k8s_info module transforms Ansible from a tool that simply pushes configurations into a sophisticated observability and orchestration engine. By leveraging the Kubernetes API, it provides a structured way to audit cluster health, track resource distribution, and implement conditional logic based on the actual state of the environment. The ability to perform server-side filtering using field_selectors and client-side transformation using Jinja2 filters like map, flatten, and selectattr allows for the creation of highly dynamic playbooks. While installation challenges exist in legacy environments—specifically those using Ansible 2.9 or outdated Python versions—adherence to the prerequisite of Ansible 2.12+ and the official kubernetes Python library ensures a stable and scalable implementation for cluster auditing and management.