Turn off host_key_checking when using Python API

We have a Python program that calls the ansible Python API – e.g.:


pb = ansible.playbook.PlayBook(
playbook=playbook,
host_list=host_list,
stats=stats,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
extra_vars=extra_vars,
private_key_file=private_key_file,
subset=host
)

pb.run()

How can I specify that I want host_key_checking off?

There are a few things that work, but I’m trying to avoid for various reasons:

  1. Putting host_key_checking = False in ansible.cfg – trying to avoid this because the user could run our tool from any directory so we don’t know that ansible.cfg will be in their current directory and we don’t want to force them to have a ~/.ansible.cfg or /etc/ansible/ansible.cfg

  2. Setting environment variable ANSIBLE_HOST_KEY_CHECKING. The following works, but it’s a little gross because it’s messing with global state and it has to be done before importing ansible for it to take effect:


os.environ['ANSIBLE_HOST_KEY_CHECKING'] = 'False'

import ansible.runner
import ansible.playbook
from ansible import callbacks

Is there some other way to just pass in a parameter or something to turn off host key checking? It doesn’t look like it from a quick scan of the code. Wonder if a PR that added an optional parameter might be something that would be considered?

Related:

https://groups.google.com/forum/#!msg/ansible-project/OuHJwG0LLTY/qp95qAq-PNUJ

Here’s another hacky way to do it:


pb = ansible.playbook.PlayBook(
playbook=playbook,
host_list=host_list,
stats=stats,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
extra_vars=extra_vars,
private_key_file=private_key_file,
subset=host
)

ansible.constants.HOST_KEY_CHECKING = False

pb.run() # This runs the playbook

but it would be cool if I could pass it to the PlayBook constructor.

Some of the v2/ refactoring will enable some new API options that may allow for making this easier - or it may be something we can entertain after those refactorings are more complete.

At this time though, it’s not a great point to get involved, as it’s still too emergent.

We will let you know when this time is.

Cool, thanks Michael!