Ansible

13.5.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates running a simple Ansible playbook programmatically using `ansible-runner`. It creates a temporary directory for Ansible to work in, defines a basic playbook, and executes it. Ensure `ansible-runner` is installed (`pip install ansible-runner`).

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.")

view raw JSON →