How do I detect whether my Python code is ran by Ansible as it's module, or is run directly by Python interpreter?

Tell me please in what way I can know inside Python3 code whether the code is running as an Ansible module as part of a playbook, for example, or whether the code was launched somehow else (by a script without TTY, or at CLI)?

I want to keep my small script as a single file, but make it usable both as a CLI utility and as an Ansible module for Ansible tasks. Yes, I can slice logic into a Python module with the logic, import the logic as a module in the CLI utility file, and separately I can import it in another file with the Ansible module.

But is there a good, reliable criterion to detect whether the parent is Ansible or not?

Thank you!

1 Like

Hello Fred [@Fred_Wood],
this is an interesting question.

I use the following function to detect whether the execution environment is Ansible:

def isAnsibleAutomation():
    """ Checks if script runs in Ansible environment
    """
    ansibleAutomationFlag: bool = False
    fileName: str = sys.argv[0]
    if "/tmp/ansible" in fileName and "payload.zip/ansible/modules" in fileName:
        ansibleAutomationFlag = True
    return ansibleAutomationFlag

I can’t say exactly how valid this approach is, but it has met my requirements so far.

Best regards
Stefan

I would not count on /tmp/ansible as that is subject to change, while looking for ‘/ansible/’ will probably not, it won’t be true when using pipelining. The same with the zip detection, which is also limited to modules using the AnsibleModule base class.

One thing that should work no matter what type of module or how execution is configured is looking for internal fields like _ansible_module_name in the arguments file, if using AnsibleModule to autoload parameters, you can check if it is None, which is the default and would indicate ansible did not run it.