import shutil
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
import ansible.constants as C
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
options = Options(connection='ssh', module_path=['/to/mymodules'], 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()
inventory = InventoryManager(loader=loader, sources=['myansible/hosts'])
variable_manager = VariableManager(loader=loader, inventory=inventory)
play_source=dict(
name="my ansible play",
hosts='webservers', # 指定在哪些主机上执行任务
gather_facts='no', # 不收集主机的信息
tasks=[ # 定义在主机上执行的任务
dict(action=dict(module='shell', args='ls -ld /home'), 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,
options=options,
passwords=passwords,
)
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)
手机扫一扫
移动阅读更方便
你可能感兴趣的文章