I copied the sample code from ansible website and changed some parameters
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
Options = namedtuple(‘Options’, [‘connection’, ‘module_path’, ‘forks’, ‘become’, ‘become_method’, ‘become_user’, ‘check’])
initialize needed objects
variable_manager = VariableManager()
loader = DataLoader()
options = Options(connection=‘ssh’, module_path=‘/home/huhe/ansible/lib/ansible/modules’, forks=100, become=None, become_method=None, become_user=None, check=False)
passwords = dict(vault_pass=‘secret’)
create inventory and pass to var manager
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=‘/etc/ansible/hosts’)
variable_manager.set_inventory(inventory)
create play with tasks
play_source = dict(
name = “Ansible Play”,
hosts = ‘linux’,
gather_facts = ‘no’,
tasks = [
dict(action=dict(module=‘shell’, args=‘ls’), 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)
actually run it
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=‘default’,
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
when i ran it, i got errors below. Any idea what is wrong?
Traceback (most recent call last):
File “/home/huhe/workspace/ansible/src/uptime.py”, line 48, in
result = tqm.run(play)
File “/home/huhe/ansible/lib/ansible/executor/task_queue_manager.py”, line 187, in run
self.load_callbacks()
File “/home/huhe/ansible/lib/ansible/executor/task_queue_manager.py”, line 156, in load_callbacks
for callback_plugin in callback_loader.all(class_only=True):
File “/home/huhe/ansible/lib/ansible/plugins/init.py”, line 349, in all
self._module_cache[path] = self._load_module_source(name, path)
File “/home/huhe/ansible/lib/ansible/plugins/init.py”, line 313, in _load_module_source
module = imp.load_source(name, path, module_file)
File “/home/huhe/ansible/lib/ansible/plugins/callback/slack.py”, line 26, in
from main import cli
ImportError: cannot import name cli