[Python] How can I ensure dependencies in a custom ansible module without having to copy the...

Discussão em 'Python' iniciado por Stack, Janeiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have created an Ansible module, but I don't want to keep everything in one file, but split it into packages. In this respect, my custom module is dependent on these packages. When I run my playbook. I get an error message ModuleNotFoundError. I have set the configuration variable DEFAULT_MODULE_PATH=./my_project/library accordingly.

    I have previously read that this library directory is then copied to the remote host and the script is then executed.

    However, when I looked at the copied scripts from Ansible on the Remote Host, various Python modules are installed there (/tmp/ansible_xxx.../), such as module_utils and ansible_collections, as well as my main module. But the additional Python packages that I created in the library directory are not there. Consequently, the call fails because the script cannot find the corresponding packages.

    Q: How can I get Ansible to deploy my dependent packages with the main script to the Remote Host? Or are there any settings in the configuration that I have missed so that the dependencies are also copied?

    NOTE: I would like to avoid running additional tasks in the playbook to install the required Python modules on the Remote Machine, as this would bloat the code unnecessarily. Also, I might have to remove them afterwards.

    An example follows here, for better understanding:

    Directory structure:

    my_project/
    ├── inv/...
    ├── playbooks/
    │ └── test_module.yml
    ├── library/
    │ ├── my_custom_module.py
    │ └── utils/
    │ ├── __init__.py
    │ └── helper.py


    my_custom_module.py:

    from ansible.module_utils.basic import AnsibleModule
    from utils.helper import some_function

    def main():
    module_args = dict(
    param=dict(type='str', required=True)
    )

    module = AnsibleModule(argument_spec=module_args)
    param = module.params['param']

    # Verwende Funktionen aus deinen Abhängigkeiten
    result = some_function(param)

    # Rückgabe an Ansible
    module.exit_json(changed=True, result=result)

    if __name__ == '__main__':
    main()


    playbooks/test_module.yml:

    - name: Test Custom-Modul
    hosts: localhost
    tasks:
    - name: call Custom-Modul
    my_custom_module:
    param: "test-value"


    I run it as:

    ansible-playbook -i localhost, my_project/playbooks/test_module.yml


    Which resulted in the following error:

    ModuleNotFoundError: No module named 'utils'

    1. I have created a test playbook
    2. I have created a test module with depencies
    3. The variable DEFAULT_MODULE_PATH customized in ansible.cfg
    4. I transferred script inspected on the Remote Host

    Continue reading...

Compartilhe esta Página