Ansible Tower CLI

raw JSON →
3.3.9 verified Thu Apr 16 auth: no python

Ansible Tower CLI (tower-cli) is a command-line interface tool for interacting with Ansible Tower and AWX instances. It allows users to manage resources like job templates, inventories, and projects directly from the terminal, and also provides a programmatic interface for Python scripts. The library is currently at version 3.3.9 and receives regular updates, typically with several minor releases focusing on bug fixes and new features throughout the year.

pip install ansible-tower-cli
error tower-cli: command not found
cause The `tower-cli` executable is not in your system's PATH, or the package was not installed correctly.
fix
Ensure ansible-tower-cli is installed via pip install ansible-tower-cli within your active Python environment. If using a virtual environment, activate it. If installed, verify your PATH includes the directory where pip installs executables (e.g., ~/.local/bin or /usr/local/bin).
error requests.exceptions.SSLError: HTTPSConnectionPool(...) Max retries exceeded with url: ... Caused by SSLError(CertificateError("hostname '...' doesn't match '...'",)
cause SSL certificate verification failed. This can happen if your Tower/AWX instance uses a self-signed certificate, or the certificate is not trusted by your system's certificate store, especially after the `verify_ssl` default changed in v3.3.2.
fix
If safe to do so (e.g., in a trusted internal network with self-signed certs), set the environment variable TOWER_VERIFY_SSL=False or use the --insecure flag with CLI commands. Otherwise, ensure your system's certificate store trusts the certificate of your Tower/AWX instance.
error Authentication required
cause Your API request to Tower/AWX was rejected due to missing or invalid authentication credentials (e.g., incorrect token, username, or password).
fix
Ensure TOWER_TOKEN environment variable is set with a valid, active API token. Alternatively, if using username/password, verify TOWER_USERNAME and TOWER_PASSWORD are correct and the user has permissions. Use tower-cli login to generate a new token.
error The requested object could not be found.
cause You attempted to access a resource (e.g., job template, inventory) by an ID or name that does not exist or is inaccessible to your authenticated user.
fix
Double-check the resource ID or name for typos. Verify that the authenticated user has appropriate read permissions on the resource you are trying to access in Ansible Tower/AWX. Use tower-cli <resource_type> list to confirm available resources and their IDs.
breaking The default behavior for `verify_ssl` changed from `False` to `True` in `v3.3.2`. If you were relying on SSL verification being off without explicitly setting it, your commands will now fail with SSL certificate errors.
fix Explicitly set `TOWER_VERIFY_SSL=False` in your environment variables, or use `--insecure` flag on the CLI, or ensure your Python environment trusts the SSL certificate of your Tower/AWX instance.
gotcha As of `v3.3.0`, `tower-cli login` introduced token-based authentication as the recommended method. While username/password can still be used directly in some commands, using API tokens is more secure and generally preferred, especially for programmatic access.
fix Use `tower-cli login` to obtain an API token and then set the `TOWER_TOKEN` environment variable for your CLI or programmatic interactions. Avoid embedding `--username` and `--password` directly in scripts or command lines.
gotcha When using `tower-cli` programmatically, configurations set via `tower_cli.get_resource('settings').modify()` persist to a local configuration file by default. This can lead to unexpected behavior if multiple scripts or users share the same configuration or if you intend for settings to be transient.
fix For transient or script-specific configurations, rely primarily on environment variables (`TOWER_HOST`, `TOWER_TOKEN`, etc.) which are picked up automatically by `tower_cli`. If you must modify settings in code, consider explicitly resetting or managing the config file location if persistence is not desired.

This quickstart demonstrates how to use `ansible-tower-cli` programmatically within a Python script. It relies on environment variables (`TOWER_HOST`, `TOWER_TOKEN`, `TOWER_VERIFY_SSL`) for configuration, which is the recommended approach for secure and flexible scripting. It then fetches and prints the first five job templates from the configured Tower/AWX instance. Ensure you have your instance details and API token set as environment variables before running.

import os
import tower_cli

# Configure tower_cli using environment variables
# Recommended: set TOWER_HOST and TOWER_TOKEN for secure authentication.
# Example: export TOWER_HOST='https://your-awx-instance.com'
#          export TOWER_TOKEN='your_api_token'
#          export TOWER_VERIFY_SSL='False' # if using self-signed certs

host = os.environ.get('TOWER_HOST', 'https://localhost')
token = os.environ.get('TOWER_TOKEN', '')
verify_ssl_str = os.environ.get('TOWER_VERIFY_SSL', 'True').lower()
verify_ssl = verify_ssl_str == 'true' or verify_ssl_str == '1'

if not token:
    print("WARNING: TOWER_TOKEN environment variable not set. This example will likely fail.")
    print("Please set TOWER_HOST and TOWER_TOKEN (and optionally TOWER_VERIFY_SSL) environment variables.")

# Programmatically set configuration, this will override environment variables if set
# This also persists to a config file by default, which can be useful but might be unintended.
# For a single script run, relying solely on env vars is often preferred.
# If you need to set explicitly in code:
# tower_cli.get_resource('settings').modify(
#     TOWER_HOST=host,
#     TOWER_TOKEN=token,
#     TOWER_VERIFY_SSL=verify_ssl
# )

print(f"Attempting to connect to Tower/AWX at: {host}")
print("Listing the first 5 job templates...")

try:
    # Using tower_cli.get_resource() to interact with the API
    # Configuration will be picked up from environment variables.
    job_templates_resource = tower_cli.get_resource('job_templates')
    job_templates = job_templates_resource.list(page_size=5)

    if job_templates:
        print("Successfully retrieved job templates:")
        for jt in job_templates:
            print(f"- ID: {jt['id']}, Name: {jt['name']}")
    else:
        print("No job templates found or access denied. Check your permissions and connection.")

except tower_cli.exceptions.TowerCLIError as e:
    print(f"An error occurred while interacting with Tower/AWX: {e}")
    print("Please ensure your TOWER_HOST, TOWER_TOKEN, and TOWER_VERIFY_SSL environment variables are correctly set and accessible.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")