ansible-compat
Examples
Using Ansible runtime
"""Sample use of Runtime class."""
import pytest
from ansible_compat.runtime import Runtime
@pytest.mark.skip(reason="external connectivity is disabled during the build process")
def test_runtime_example() -> None:
"""Test basic functionality of Runtime class."""
# instantiate the runtime using isolated mode, so installing new
# roles/collections do not pollute the default setup.
runtime = Runtime(isolated=True, max_retries=3)
# Print Ansible core version
print(runtime.version) # 2.9.10 (Version object)
# Get configuration info from runtime
print(runtime.config.collections_path)
# Detect if current project is a collection and install its requirements
runtime.prepare_environment(install_local=True) # will retry 3 times if needed
# Install a new collection (will retry 3 times if needed)
runtime.install_collection("containers.podman")
# Execute a command
result = runtime.exec(["ansible-doc", "--list"])
assert result.returncode == 0
Access to Ansible configuration
As you may not want to parse ansible-config dump
yourself, you
can make use of a simple python class that facilitates access to
it, using python data types.
"""Sample usage of AnsibleConfig."""
from ansible_compat.config import AnsibleConfig
def test_example_config() -> None:
"""Test basic functionality of AnsibleConfig."""
cfg = AnsibleConfig()
assert isinstance(cfg.ACTION_WARNINGS, bool)
# you can also use lowercase:
assert isinstance(cfg.action_warnings, bool)
# you can also use it as dictionary
assert cfg['action_warnings'] == cfg.action_warnings
API
Ansible runtime environment maanger.
- class ansible_compat.runtime.Runtime(project_dir: Optional[str] = None, isolated: bool = False, min_required_version: Optional[str] = None, require_module: bool = False, max_retries: int = 0, environ: Optional[Dict[str, str]] = None)[source]
Ansible Runtime manager.
- __init__(project_dir: Optional[str] = None, isolated: bool = False, min_required_version: Optional[str] = None, require_module: bool = False, max_retries: int = 0, environ: Optional[Dict[str, str]] = None) None [source]
Initialize Ansible runtime environment.
- Parameters
project_dir – The directory containing the Ansible project. If not mentioned it will be guessed from the current working directory.
isolated – Assure that installation of collections or roles does not affect Ansible installation, an unique cache directory being used instead.
min_required_version – Minimal version of Ansible required. If not found, a
RuntimeError
exception is raised.max_retries – Number of times it should retry network operations. Default is 0, no retries.
environ – Environment dictionary to use, if undefined
os.environ
will be copied and used.
- Param
require_module: If set, instantiation will fail if Ansible Python module is missing or is not matching the same version as the Ansible command line. That is useful for consumers that expect to also perform Python imports from Ansible.
- exec(args: Union[str, List[str]], retry: bool = False, tee: bool = False, env: Optional[Dict[str, str]] = None, cwd: Optional[str] = None) subprocess.CompletedProcess [source]
Execute a command inside an Ansible environment.
- Parameters
retry – Retry network operations on failures.
tee – Also pass captured stdout/stderr to system while running.
- install_collection(collection: str, destination: Optional[Union[str, pathlib.Path]] = None, force: bool = False) None [source]
Install an Ansible collection.
Can accept version constraints like ‘foo.bar:>=1.2.3’
- install_collection_from_disk(path: str, destination: Optional[Union[str, pathlib.Path]] = None) None [source]
Build and install collection from a given disk path.
- install_requirements(requirement: str, retry: bool = False) None [source]
Install dependencies from a requirements.yml.
- prepare_environment(required_collections: Optional[Dict[str, str]] = None, retry: bool = False, install_local: bool = False) None [source]
Make dependencies available if needed.
- require_collection(name: str, version: Optional[str] = None, install: bool = True) None [source]
Check if a minimal collection version is present or exits.
In the future this method may attempt to install a missing or outdated collection before failing.
- property version: packaging.version.Version
Return current Version object for Ansible.
If version is not mentioned, it returns current version as detected. When version argument is mentioned, it return converts the version string to Version object in order to make it usable in comparisons.