From 1160e506e92bb959a2fa514c6cbcc9ab932d2317 Mon Sep 17 00:00:00 2001 From: Brian Coca Date: Tue, 5 Mar 2019 16:07:53 -0500 Subject: [PATCH] write to file option for ansible-inventory (#53183) * write to file option for ansible-inventory * changed comment, ensure text mode --- lib/ansible/cli/inventory.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/ansible/cli/inventory.py b/lib/ansible/cli/inventory.py index f011f0d5637..a1ee255488a 100644 --- a/lib/ansible/cli/inventory.py +++ b/lib/ansible/cli/inventory.py @@ -14,6 +14,7 @@ from ansible.cli import CLI from ansible.cli.arguments import optparse_helpers as opt_help from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.inventory.host import Host +from ansible.module_utils._text import to_bytes, to_native from ansible.plugins.loader import vars_loader from ansible.utils.vars import combine_vars from ansible.utils.display import Display @@ -86,6 +87,8 @@ class InventoryCLI(CLI): self.parser.add_option("--export", action="store_true", default=C.INVENTORY_EXPORT, dest='export', help="When doing an --list, represent in a way that is optimized for export," "not as an accurate representation of how Ansible has processed it") + self.parser.add_option('--output', default=None, dest='output_file', + help="When doing an --list, send the inventory to a file instead of of to screen") # self.parser.add_option("--ignore-vars-plugins", action="store_true", default=False, dest='ignore_vars_plugins', # help="When doing an --list, skip vars data from vars plugins, by default, this would include group_vars/ and host_vars/") @@ -145,8 +148,16 @@ class InventoryCLI(CLI): results = self.dump(results) if results: - # FIXME: pager? - display.display(results) + outfile = context.CLIARGS['output_file'] + if outfile is None: + # FIXME: pager? + display.display(results) + else: + try: + with open(to_bytes(outfile), 'wt') as f: + f.write(results) + except (OSError, IOError) as e: + raise AnsibleError('Unable to write to destination file (%s): %s' % (to_native(outfile), to_native(e))) exit(0) exit(1)