Python module API for Ansible Galaxy

Hi all. I was wondering if there is a way to use Ansible Galaxy from within Python.

I’m familiar with using Ansible Galaxy in the CLI:

ansible-galaxy collection install /path/to/ansible-galaxy-requirements.yml

I’d like to be able to do something like this:

from ansible import galaxy

galaxy.install({
    'collections': ['community.general', 'community.mysql'],
    'roles': ['geerlingguy.php'],
})

On that note, it would be really cool if I could specify versions as well, but I’d be happy with just the above as well.

Is something like this currently possible or supported in a future version? Thanks in advance.

Kind regards

1 Like

TL;DR: No

Outside of the plugin APIs, none of the python code of ansible-core should be considered a public API. Effectively, in practice that means that the ability to run any of the functionality of the ansible CLIs is not supported by any public API.

1 Like

Thanks for the clarification on ansible-core code @sivel!

But maybe there’s some other way, even if it’s a 3rd party lib. Or some quick’n’dirty hack.

Isn’t galaxy based on pulp? I’m not sure there, but if I’m right: Maybe there’s a way to automatically build a client for pulp based repositories?

I’m just wildly guessing around, and possibly on completely wrong assumptions!

Could you help me understand why calling the command doesn’t work for you?

1 Like

@Belal A number of programmatic APIs for CLI tools are wrapping calls to the CLI tool, and the same approach could be used here if you’d like:

import subprocess

def ansible_galaxy(*args: str) -> None:
    subprocess.run(
        ["ansible-galaxy", *args],
        check=True,
        text=True,
    )

ansible_galaxy("collection", "install", "community.general", "community.mysql")
ansible_galaxy("role", "install", "geerlingguy.php")

The result would look like this:

➤ python3 test.py
Starting galaxy collection install process
Nothing to do. All requested collections are already installed. If you want to reinstall them, consider using `--force`.
Starting galaxy role install process
- downloading role 'php', owned by geerlingguy
- downloading role from https://github.com/geerlingguy/ansible-role-php/archive/6.0.0.tar.gz
- extracting geerlingguy.php to /home/mark/.config/ansible/roles/geerlingguy.php
- geerlingguy.php (6.0.0) was installed successfully
1 Like