Last active
March 3, 2020 09:10
-
-
Save smashwilson/f11aa1a6217ed1dacc97f6df380f5b2a to your computer and use it in GitHub Desktop.
Dynamic inventory that sets ansible_python_interpreter for localhost correctly, even within a virtualenv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Generate a "localhost" entry dynamically that uses a local connection and | |
# the same Python interpreter that's being used to execute this inventory | |
# script, which will work properly within a virtualenv. | |
import argparse | |
import json | |
import os | |
import sys | |
parser = argparse.ArgumentParser(description='Ansible dynamic inventory.') | |
group = parser.add_mutually_exclusive_group() | |
group.add_argument('--list', action='store_true', help='List host groups') | |
group.add_argument('--host', metavar='HOSTNAME', help='Return host vars') | |
args = parser.parse_args() | |
host_vars = { | |
'ansible_connection': 'local', | |
'ansible_python_interpreter': sys.executable | |
} | |
if args.list: | |
groups = { | |
'local': { | |
'hosts': ['localhost'], | |
'vars': host_vars | |
} | |
} | |
json.dump(groups, sys.stdout) | |
elif args.host: | |
if args.host == 'localhost': | |
json.dump(host_vars, sys.stdout) | |
else: | |
print '{}' | |
else: | |
parser.print_help(sys.stderr) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment