Last Updated: September 29, 2021
·
7.011K
· bcoca

executable playbooks

Using the shebang you can do nifty stuff like set default options for a playbook, also people don't even realize they are executing ansible.

#!/usr/bin/env ansible-playbook -i ../hosts -K
---
- hosts: ...

This is specially useful when running from a config/ops repo checkout which includes your hosts, hostvars and groupvars.

  • remember to make the playbook executable
  • if you run ansible-playbook playbook.yml, the shebang gets ignored

3 Responses
Add your response

This will work fine (and is a clever trick) when you don't need to pass any arguments to ansible-playbook, but is very likely to fail when you pass along extra arguments.

This is because on many platforms, the shebang line is very limited and accepts only a program (which is already taken up by /usr/bin/env in this case) and takes everything that follows as a single argument to that executable.

For more info on this, see http://stackoverflow.com/a/4304187

over 1 year ago ·

I like this idea. But my understanding is that setting options with the ansible-playbook command with this method will work in OS X, but not in Linux, for the reason zoni describes. In Linux you can only supply a program name and one option.

You can run a playbook on Linux this way with no options specified:

#!/usr/bin/env ansible-playbook

Or if you are willing to assume the location of ansible-playbook, you can supply one option, as long as it does not contain spaces:

#!/usr/bin/ansible-playbook --inventory=../hosts

Notice the use of the long-form switch, which does not have a space between --inventory and ../hosts

over 1 year ago ·

Actually, the non /usr/bin/env form doesn't work at all under MacOS X, because Darwin requires that the shebang interpreter be an executable binary program (not another shebang script) and all the Ansible commands are actually Python scripts. See http://stackoverflow.com/questions/9988125/shebang-pointing-to-script-also-having-shebang-is-effectively-ignored

over 1 year ago ·