Last active
October 14, 2020 17:18
-
-
Save grafuls/31ed13ae9adb47ec5f09513326194cb7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from __future__ import (absolute_import, division, print_function) | |
__metaclass__ = type | |
import shutil | |
import ansible.constants as C | |
from ansible.executor.task_queue_manager import TaskQueueManager | |
from ansible.module_utils.common.collections import ImmutableDict | |
from ansible.inventory.manager import InventoryManager | |
from ansible.parsing.dataloader import DataLoader | |
from ansible.playbook.play import Play | |
from ansible.plugins.callback import CallbackBase | |
from ansible.vars.manager import VariableManager | |
from ansible import context | |
# Create a callback plugin so we can capture the output | |
class ResultsCollectorJSONCallback(CallbackBase): | |
"""A sample callback plugin used for performing an action as results come in. | |
If you want to collect all results into a single object for processing at | |
the end of the execution, look into utilizing the ``json`` callback plugin | |
or writing your own custom callback plugin. | |
""" | |
def __init__(self, *args, **kwargs): | |
super(ResultsCollectorJSONCallback, self).__init__(*args, **kwargs) | |
self.host_ok = {} | |
self.host_unreachable = {} | |
self.host_failed = {} | |
def v2_runner_on_unreachable(self, result): | |
host = result._host | |
self.host_unreachable[host.get_name()] = result | |
def v2_runner_on_ok(self, result, *args, **kwargs): | |
"""Print a json representation of the result. | |
Also, store the result in an instance attribute for retrieval later | |
""" | |
host = result._host | |
self.host_ok[host.get_name()] = result | |
def v2_runner_on_failed(self, result, *args, **kwargs): | |
host = result._host | |
self.host_failed[host.get_name()] = result | |
def main(): | |
host_list = ['f21-x-r620.xxx.com'] | |
options = dict( | |
syntax=False, | |
timeout=30, | |
connection='ssh', | |
forks=10, | |
remote_user='root', | |
private_key_file='/home/user/.ssh/id_rsa', | |
become=None, | |
become_method=None, | |
become_user=None, | |
verbosity=1, | |
check=False, | |
diff=False, | |
start_at_task=None, | |
gathering='implicit', | |
remote_tmp='/tmp/.ansible' | |
) | |
context.CLIARGS = ImmutableDict(options) | |
sources = ','.join(host_list) | |
if len(host_list) == 1: | |
sources += ',' | |
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files | |
passwords = dict(vault_pass='secret') | |
results_callback = ResultsCollectorJSONCallback() | |
inventory = InventoryManager(loader=loader, sources=sources) | |
variable_manager = VariableManager(loader=loader, inventory=inventory) | |
tqm = TaskQueueManager( | |
inventory=inventory, | |
variable_manager=variable_manager, | |
loader=loader, | |
passwords=passwords, | |
stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout | |
) | |
play_source = dict( | |
name="Ansible Play", | |
hosts=host_list, | |
gather_facts='no', | |
tasks=[ | |
dict(action=dict(module='setup')), | |
] | |
) | |
play = Play().load(play_source, variable_manager=variable_manager, loader=loader) | |
try: | |
result = tqm.run(play) # most interesting data for a play is actually sent to the callback's methods | |
finally: | |
tqm.cleanup() | |
if loader: | |
loader.cleanup_all_tmp_files() | |
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True) | |
print("UP ***********") | |
for host, result in results_callback.host_ok.items(): | |
for key, fact in result._result['ansible_facts'].items(): | |
if type(fact)==dict and fact.get('type') and fact.get('type')=="ether": | |
if fact.get('device'): | |
print(f"Name: {fact['device']}") | |
if fact.get('alias'): | |
print(f"Name: {fact['alias']}") | |
if fact.get("ipv4"): | |
print(f"IPv4: {fact['ipv4']}") | |
else: | |
print(f"IPv4: NO DATA") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment