I'm looking for a way to test, in my python script, if said script is running from Ansible so I can also run it through shell (for running unit tests etc). Calling AnsibleModule without calling from an ansible playbook will just endlessly wait for a response that will never come.
I'm expecting that there isn't a simple test and that I have to restructure in some way, but I'm open to any options.
def main():
# must test if running via ansible before next line
module = AnsibleModule(
argument_spec=dict(
server=dict(required=True, type='str'),
[...]
)
[... do things ...]
)
if __name__ == "__main__":
if running_via_ansible:
main()
else:
run_tests()
I believe there are a couple of answers, with various levels of trickery involved
sys.argv[0]
will start with AnsiballZ_
; it will also likely be written to $HOME/.ansible/tmp
on the target machine, so one could sniff for .ansible/tmp
showing up in argv[0]
alsoWANT_JSON
in it, then ansible will invoke it with the module's JSON payload as the first argument instead of feeding it JSON on sys.stdin
(thus far the filename has been colocated with the AnsiballZ_
script, but I don't know that such a thing is guaranteed) """<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>"""
(or the '''
flavor works, too) then that magic string is replaced by the serialized JSON that, again, would have been otherwise provided via stdinWhile this may not apply, or be helpful, I actually would expect that any local testing environment would have more "fingerprints" than trying to detect the opposite, and has the pleasing side-effect of "failing open" in that the module will assume it is running in production mode unless it can prove testing mode, which should make for less weird false positives. Then again, I guess the reasonable default depends on how problematic it would be for the module to attempt to carry out its payload when not really in use
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.