CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-ansible-runner

Consistent Ansible Python API and CLI with container and process isolation runtime capabilities

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

command-execution.mddocs/

Command Execution

Execute Ansible command-line tools (ansible-playbook, ansible, ansible-inventory, etc.) programmatically with full argument support and output capture. Provides a consistent interface for running any Ansible command with process isolation and event handling capabilities.

Capabilities

Synchronous Command Execution

Execute Ansible commands and wait for completion. Returns a Runner instance with command output, return codes, and execution artifacts.

def run_command(
    executable_cmd: str,
    cmdline_args: list = None,
    private_data_dir: str = None,
    input_fd: object = None,
    output_fd: object = None,
    error_fd: object = None,
    quiet: bool = False,
    artifact_dir: str = None,
    ident: str = None,
    rotate_artifacts: int = 0,
    timeout: int = None,
    runner_mode: str = 'pexpect',
    process_isolation: bool = False,
    process_isolation_executable: str = None,
    process_isolation_path: str = None,
    process_isolation_hide_paths: list = None,
    process_isolation_show_paths: list = None,
    process_isolation_ro_paths: list = None,
    container_image: str = None,
    container_volume_mounts: list = None,
    container_options: list = None,
    directory_isolation_base_path: str = None,
    envvars: dict = None,
    cancel_callback: callable = None,
    finished_callback: callable = None,
    status_handler: callable = None,
    event_handler: callable = None,
    artifacts_handler: callable = None,
    ignore_logging: bool = True,
    debug: bool = None,
    logfile: str = None
) -> Runner

Parameters:

  • executable_cmd (str): Ansible command to execute (e.g., 'ansible-playbook', 'ansible', 'ansible-inventory')
  • cmdline_args (list): Command-line arguments as a list of strings
  • private_data_dir (str): Directory for input files and output artifacts
  • timeout (int): Maximum execution time in seconds
  • process_isolation (bool): Enable container-based execution
  • envvars (dict): Environment variables to set during execution

Usage examples:

import ansible_runner

# Run ansible-playbook command
result = ansible_runner.run_command(
    executable_cmd='ansible-playbook',
    cmdline_args=[
        'site.yml',
        '-i', 'inventory/hosts',
        '--extra-vars', 'env=production',
        '--check'
    ],
    private_data_dir='/path/to/private_data'
)

print(f"Command completed with return code: {result.rc}")
print(f"Status: {result.status}")

# Run ansible ad-hoc command
result = ansible_runner.run_command(
    executable_cmd='ansible',
    cmdline_args=[
        'all',
        '-i', 'inventory/hosts',
        '-m', 'setup',
        '--tree', '/tmp/facts'
    ],
    private_data_dir='/path/to/private_data'
)

# Run ansible-inventory command
result = ansible_runner.run_command(
    executable_cmd='ansible-inventory',
    cmdline_args=[
        '-i', 'inventory/hosts',
        '--list',
        '--yaml'
    ],
    private_data_dir='/path/to/private_data'
)

Asynchronous Command Execution

Execute Ansible commands asynchronously for non-blocking operation with callback-based monitoring.

def run_command_async(
    executable_cmd: str,
    cmdline_args: list = None,
    private_data_dir: str = None,
    input_fd: object = None,
    output_fd: object = None,
    error_fd: object = None,
    quiet: bool = False,
    artifact_dir: str = None,
    ident: str = None,
    rotate_artifacts: int = 0,
    timeout: int = None,
    runner_mode: str = 'pexpect',
    process_isolation: bool = False,
    process_isolation_executable: str = None,
    process_isolation_path: str = None,
    process_isolation_hide_paths: list = None,
    process_isolation_show_paths: list = None,
    process_isolation_ro_paths: list = None,
    container_image: str = None,
    container_volume_mounts: list = None,
    container_options: list = None,
    directory_isolation_base_path: str = None,
    envvars: dict = None,
    cancel_callback: callable = None,
    finished_callback: callable = None,
    status_handler: callable = None,
    event_handler: callable = None,
    artifacts_handler: callable = None,
    ignore_logging: bool = True,
    debug: bool = None,
    logfile: str = None
) -> Runner

Usage example:

import ansible_runner
import time

def command_status_handler(data, runner_config):
    print(f"Command status: {data['status']}")

# Start async command execution
runner = ansible_runner.run_command_async(
    executable_cmd='ansible-playbook',
    cmdline_args=['long-running-playbook.yml', '-i', 'inventory'],
    private_data_dir='/path/to/private_data',
    status_handler=command_status_handler
)

# Monitor progress
while runner.status in ['pending', 'running']:
    print("Command still executing...")
    time.sleep(2)

print(f"Command finished with status: {runner.status}")

Common Use Cases

Ansible Playbook Execution

# Basic playbook run
result = ansible_runner.run_command(
    executable_cmd='ansible-playbook',
    cmdline_args=['site.yml', '-i', 'hosts'],
    private_data_dir='/project'
)

# Playbook with extra variables and verbosity
result = ansible_runner.run_command(
    executable_cmd='ansible-playbook',
    cmdline_args=[
        'deploy.yml',
        '-i', 'production',
        '--extra-vars', '@vars/production.yml',
        '--limit', 'webservers',
        '-vvv'
    ],
    private_data_dir='/project'
)

# Dry run (check mode)
result = ansible_runner.run_command(
    executable_cmd='ansible-playbook',
    cmdline_args=['site.yml', '-i', 'hosts', '--check', '--diff'],
    private_data_dir='/project'
)

Ad-hoc Commands

# Gather facts from all hosts
result = ansible_runner.run_command(
    executable_cmd='ansible',
    cmdline_args=[
        'all',
        '-i', 'inventory',
        '-m', 'setup'
    ],
    private_data_dir='/project'
)

# Execute shell command on specific hosts
result = ansible_runner.run_command(
    executable_cmd='ansible',
    cmdline_args=[
        'webservers',
        '-i', 'inventory',
        '-m', 'shell',
        '-a', 'uptime'
    ],
    private_data_dir='/project'
)

# Copy files to remote hosts
result = ansible_runner.run_command(
    executable_cmd='ansible',
    cmdline_args=[
        'all',
        '-i', 'inventory',
        '-m', 'copy',
        '-a', 'src=/local/file dest=/remote/file'
    ],
    private_data_dir='/project'
)

Inventory Operations

# List inventory in JSON format
result = ansible_runner.run_command(
    executable_cmd='ansible-inventory',
    cmdline_args=['-i', 'inventory', '--list'],
    private_data_dir='/project'
)

# Show inventory for specific host
result = ansible_runner.run_command(
    executable_cmd='ansible-inventory',
    cmdline_args=['-i', 'inventory', '--host', 'web01'],
    private_data_dir='/project'
)

# Export inventory graph
result = ansible_runner.run_command(
    executable_cmd='ansible-inventory',
    cmdline_args=['-i', 'inventory', '--graph'],
    private_data_dir='/project'
)

Ansible Configuration

# View current configuration
result = ansible_runner.run_command(
    executable_cmd='ansible-config',
    cmdline_args=['view'],
    private_data_dir='/project'
)

# List all configuration options
result = ansible_runner.run_command(
    executable_cmd='ansible-config',
    cmdline_args=['list'],
    private_data_dir='/project'
)

# Dump configuration
result = ansible_runner.run_command(
    executable_cmd='ansible-config',
    cmdline_args=['dump'],
    private_data_dir='/project'
)

Advanced Usage

Process Isolation

Run commands in isolated containers for security and reproducibility:

result = ansible_runner.run_command(
    executable_cmd='ansible-playbook',
    cmdline_args=['site.yml', '-i', 'inventory'],
    private_data_dir='/project',
    process_isolation=True,
    process_isolation_executable='podman',
    container_image='quay.io/ansible/ansible-runner:latest',
    container_volume_mounts=['/host/keys:/runner/keys:Z'],
    envvars={'ANSIBLE_HOST_KEY_CHECKING': 'False'}
)

Custom Environment Variables

result = ansible_runner.run_command(
    executable_cmd='ansible-playbook',
    cmdline_args=['site.yml'],
    private_data_dir='/project',
    envvars={
        'ANSIBLE_HOST_KEY_CHECKING': 'False',
        'ANSIBLE_TIMEOUT': '30',
        'ANSIBLE_GATHERING': 'smart'
    }
)

Output Handling

import tempfile

# Capture output to files
with tempfile.NamedTemporaryFile(mode='w+') as stdout_file, \
     tempfile.NamedTemporaryFile(mode='w+') as stderr_file:
    
    result = ansible_runner.run_command(
        executable_cmd='ansible-playbook',
        cmdline_args=['site.yml'],
        private_data_dir='/project',
        output_fd=stdout_file,
        error_fd=stderr_file
    )
    
    # Read captured output
    stdout_file.seek(0)
    stderr_file.seek(0)
    stdout_content = stdout_file.read()
    stderr_content = stderr_file.read()

Install with Tessl CLI

npx tessl i tessl/pypi-ansible-runner

docs

command-execution.md

configuration-runner.md

index.md

playbook-execution.md

plugin-role-management.md

streaming-distributed.md

utilities-cleanup.md

tile.json