Ansible
Ansible is a radically simple IT automation engine that automates cloud provisioning, configuration management, application deployment, intra-service orchestration, and other IT needs. The `ansible` PyPI package (currently v13.5.0) is a meta-package that bundles `ansible-core` (the engine) and various `ansible-collections` for modules and plugins. It follows a release cadence tied to the `ansible-core` and collection ecosystem, with major updates typically released quarterly.
Warnings
- gotcha The `ansible` PyPI package is a meta-package. It installs `ansible-core` and many `ansible-collections`. For minimal setups or specific programmatic tasks, `pip install ansible-core` or `pip install ansible-runner` might be sufficient and lead to a smaller installation footprint.
- breaking Python version compatibility changes frequently with `ansible-core` releases. Newer `ansible-core` versions drop support for older Python versions. The `ansible` meta-package version 13.5.0 requires Python >=3.12, reflecting its underlying `ansible-core` 2.16.x.
- gotcha Directly importing from `ansible.*` internal modules (e.g., `ansible.playbook`, `ansible.executor`) for programmatic interaction is generally discouraged. These are internal APIs and are subject to change without warning between versions, leading to unstable code.
- breaking Major version upgrades of `ansible-core` (e.g., 2.9 to 2.10, 2.11 to 2.12, etc.) frequently introduce breaking changes in module arguments, plugin interfaces, and internal data structures. This can affect custom modules, plugins, or scripts that directly interact with Ansible's internals.
Install
-
pip install ansible -
pip install ansible-core -
pip install ansible-runner
Imports
- run
from ansible_runner import run
Quickstart
import os
import shutil
import ansible_runner
# Define a simple playbook
playbook_content = """
- name: Hello Ansible
hosts: localhost
gather_facts: no
tasks:
- name: Display message
ansible.builtin.debug:
msg: "Ansible is running from Python!"
"""
# Create a temporary directory for the run
temp_dir = "./ansible_quickstart_temp"
os.makedirs(temp_dir, exist_ok=True)
# Write the playbook to a file in the temp directory
playbook_path = os.path.join(temp_dir, "hello.yml")
with open(playbook_path, "w") as f:
f.write(playbook_content)
try:
# Run the playbook using ansible-runner
# private_data_dir is essential for ansible-runner to function
r = ansible_runner.run(
private_data_dir=temp_dir,
playbook="hello.yml",
inventory={"localhost": {"hosts": ["localhost"]}}, # Minimal inventory
quiet=True # Suppress some verbose output
)
print(f"\nAnsible Runner Status: {r.status}")
if r.rc == 0:
print("Playbook executed successfully.")
# Optionally, print captured stdout from events
for event in r.events:
if 'event' in event and event['event'] == 'runner_on_ok' and 'msg' in event['event_data']['res']:
print(f" Task output: {event['event_data']['res']['msg']}")
else:
print(f"Playbook failed with return code: {r.rc}")
print(f"Errors: {r.stderr}") # ansible-runner captures stderr
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Clean up the temporary directory
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
print("Cleanup complete.")