Ansible API 2.9.5 给host配置密码访问

分类:Python, 发布于 2020-03-05 15:05:43,浏览(146),评论(0)

直接上例子,顺便Mark备注。

import json
import shutil
from ansible.module_utils.common.collections import ImmutableDict
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
from ansible import context
import ansible.constants as C
class ResultCallback(CallbackBase):
    def v2_runner_on_ok(self, result, **kwargs):
        host = result._host
        print(json.dumps({host.name: result._result}, indent=4))
    def v2_runner_on_failed(self, result, ignore_errors=False):
        print('FAILED! => task: %s; message: %s', result._task, self._dump_results(result._result))
    def v2_runner_on_unreachable(self, result):
        print('UNREACHABLE! =>  message: %s', result._task, self._dump_results(result._result))
context.CLIARGS = ImmutableDict(connection='ssh',module_path=None, verbosity=5, forks=10, become=None, become_method=None, become_user=None, check=False, diff=False)
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
#passwords = dict(vault_pass='123456')
passwords = {}
inventory = InventoryManager(loader=loader, sources=None)
results_callback = ResultCallback()
host_list = ['192.168.3.6','192.168.3.7']
inventory.add_group('node')
for h in host_list:
    inventory.add_host(host=h, group='node')
#inventory = InventoryManager(loader=loader, sources='inventory_file')
host = inventory.get_host(hostname='192.168.3.6')
variable_manager = VariableManager(loader=loader, inventory=inventory)
#print(host_vars)
host.set_variable('ansible_ssh_user', 'user')
host.set_variable('ansible_ssh_pass', 'pass')
play_source =  dict(
        name = "node1",
        hosts = '192.168.3.6',
        gather_facts = 'no',
        tasks = [
            dict(action=dict(module='shell', args='whoami'), register='shell_out')
            #dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
         ]
    )
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
tqm = None
try:
    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
          )
    result = tqm.run(play)
finally:
    if tqm is not None:
        tqm.cleanup()
    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

这种方式需要服务安装sshpass,当然更推荐使用免密登录

评论: