Ansible Compat
Ansible Compat is a Python library providing essential compatibility layers and utilities for Ansible projects, primarily benefiting Ansible collection developers. It helps in managing forward and backward compatibility across different Ansible core versions by abstracting away API differences and simplifying interactions with Ansible's runtime. The current version is 26.3.0, and releases are typically aligned with major Ansible core updates or significant feature enhancements.
Warnings
- breaking Version 26.0.0 introduced significant internal refactoring related to collection and role loading logic, specifically adapting to changes in `ansible-core` 2.15+. Code that relied on direct access to internal path attributes (e.g., `_ansible_collection_path`) may no longer work.
- gotcha Ansible Compat has tight Python version requirements, which can also be influenced by its `ansible-core` dependency. For `ansible-compat` 26.x, Python 3.10+ is required.
- gotcha `ansible-compat` is highly dependent on `ansible-core`. Using mismatched versions (e.g., `ansible-compat` expecting `ansible-core` 2.15+ but finding an older version) can lead to runtime errors or unexpected behavior.
- gotcha When working in non-standard Ansible environments (e.g., custom `ansible.cfg` locations, unique collection paths, or isolated virtual environments), `AnsibleRuntime` and `AnsibleCompatConfig` might not automatically discover all desired settings by default.
Install
-
pip install ansible-compat
Imports
- AnsibleCompatConfig
from ansible_compat.config import AnsibleCompatConfig
- AnsibleRuntime
from ansible_compat.runtime import AnsibleRuntime
- AnsibleCollectionConfig
from ansible_compat.primitives import AnsibleCollectionConfig
- AnsiblePath
from ansible_compat.primitives import AnsiblePath
Quickstart
from ansible_compat.config import AnsibleCompatConfig
from ansible_compat.runtime import AnsibleRuntime
from ansible_compat.primitives import AnsiblePath
import os
# Initialize configuration (can be empty for defaults, or load from ansible.cfg)
config = AnsibleCompatConfig()
# Initialize runtime, which discovers Ansible paths and settings
runtime = AnsibleRuntime()
print(f"Ansible core version: {runtime.ansible_version}")
print(f"Ansible config file: {runtime.config_file or 'Not found'}")
print(f"Ansible collection paths: {runtime.ansible_collection_paths}")
# Example: Get path for a specific collection
collection_name = os.environ.get('ANSIBLE_TEST_COLLECTION', 'community.general')
collection_path = runtime.get_collection_path(collection_name)
if collection_path:
print(f"Collection '{collection_name}' found at: {collection_path}")
else:
print(f"Collection '{collection_name}' not found. Try setting it via ANSIBLE_TEST_COLLECTION.")
# Example: Using an AnsiblePath primitive
some_path = AnsiblePath("my_ansible_artifact.yml")
print(f"AnsiblePath object for 'my_ansible_artifact.yml': {some_path}")