How to Detect if Python is Executing in Ansible Context

Posted on

Hello Community,

at the moment I am trying to develop Python code that can be executed unchanged on different platforms. For this I have built a function that analyzes the name of the script and detects on this way whether the Python code is executed in the context of Ansible. How valid is this approach? Does the name created by Ansible often change from release to release? Or is there another more stable way to detect whether the Python code is executed in the context of Ansible or not?

Thanks for hints and tips.
Best regards
Stefan

def isAnsibleAutomation():

    ansibleAutomationFlag = False

    fileName = sys.argv[0]
    if "/tmp/ansible" in fileName and "payload.zip/ansible/modules" in fileName:
        ansibleAutomationFlag = True

    return ansibleAutomationFlag

Responses