/ Ansible / Python

Ansible para conexión a windows con Python

Hola a todos!

Si se necesita manejar Ansible de forma dinámica y para ejecutar comandos en entornos windows que no tengan winRM, entonces usa SMB. O el bien conocido PSEXEC. 

PSEXEC también llega como módulo en Ansible. Por ende es necesario instalar los requerimientos para este módulo. Para esto recomiendo seguir la documentación oficial:

Una vez instalado los requerimientos se puede pasar a ver y analizar el siguiente Script:

import shutil
import json
import yaml
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
import ansible.constants as C
#CLASS TO COLLECT RESULT
class ResultCallback(CallbackBase):
def v2_runner_on_ok(self, result, **kwargs):
host = result._host
print(result._result)
print(json.dumps({host.name: result._result}, indent=4))
def v2_runner_on_unreachable(self, result):
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
def v2_runner_on_failed(self, result, *args, **kwargs):
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
#CREDENTIALS
remote_host="1.1.1.1"
remote_user="DOMINIOusuario"
remote_password="Contraseña$"
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'remote_user', 'password','become_method', 'become_user', 'check', 'diff','verbosity',])
options = Options(connection='ssh', module_path=None, forks=10, become=False, remote_user=remote_user, password=remote_password,become_method=None, become_user=True, check=False, diff=False, verbosity=True,)
# initialize needed objects
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
passwords = {}
# Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
results_callback = ResultCallback()
# create inventory, use path to host config file as source or hosts in a comma separated string
inventory = InventoryManager(loader=loader, sources=remote_host+',')
# variable manager takes care of merging all the different sources to give you a unifed view of variables available in each context
variable_manager = VariableManager(loader=loader, inventory=inventory)
variable_manager.extra_vars = {'ansible_user': 'root', 'ansible_password': 'CONTRASEÃA DE NODO MAESTRO'}
yamlConfigFile = """
name: remote psexec
hosts: localhost
tasks:
- name: Run a cmd.exe command
psexec:
hostname: IP REMOTA
connection_username: DOMINIOUSUARIO
connection_password: CONTRASEÃA
executable: cmd.exe
arguments: /c COMANDOS DE WINDOWS
"""
theDict = yaml.load(yamlConfigFile)
play_source = theDict
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
tqm = None
#EXECUTER
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout #COLLECTOR
)
result = tqm.run(play) # most interesting data for a play is actually sent to the callback's methods
finally:
# we always need to cleanup child procs and the structres we use to communicate with them
if tqm is not None:
tqm.cleanup()
# Remove ansible tmpdir
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

Eso es todo!