Custom Ansible collection module - not able to import from Ansible.parsing.vault

Hello!

Issue: I am creating a custom collection and inside my Python script, I want to import VaultLib and VaultSecret from ansible.parsing.vault. I am installing the collection in a private automation hub, as well as inside of an execution environment.

When running a playbook using the collection, I receive an error stating that VaultLib and VaultSecret are not defined. Basically, the library is not being imported. In the docs, I’ve seen where it’s mentioned that you can only import from ansible.module_utils from inside a module. Is this a true statement? Is there some other way to import this library inside of the custom module? Thank you for your help!

1 Like

Yes, that’s true.

Vault is something you can only use on the controller / in the controller environment itself. Modules generally don’t run in the controller environment (even with connection: local, they might use another Python).

But you could create an action plugin instead. That is executed on the controller in the controller’s context, and can import and use everything from ansible-core. It can also execute a module (or multiple modules).

The most famous action plugin is probably the ansible.builtin.template “module”, which is in fact an action plguin: the templating happens on the controller (since only there you have access to all variables and even to vault), and then template action uses the ansible.builtin.copy module to copy the result (put into a temporary file) to the target.

1 Like

(I’ve moved this discussion to the Collection Development category. Development questions are better suited there.)

3 Likes

This isn’t strictly accurate; it actually uses the ansible.legacy.copy action to copy the resulting file, which can then call either the ansible.legacy.copy module or the ansible.legacy.file module (if the file contents are already correct.)

1 Like