使用Ansible2.6 Python Api执行playbook任务
以下是ansible api部分:
import json
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
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.plugins.callback import CallbackBase
import ansible.constants as C
class ResultCallback(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 v2_runner_on_ok(self, result, **kwargs):
"""Print a json representation of the result
This method could store the result in an instance attribute for retrieval later
"""
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
Options = namedtuple('Options', [
'listtags', 'listtasks', 'listhosts', 'syntax', 'connection',
'module_path', 'forks', 'remote_user', 'private_key_file', 'timeout',
'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
'scp_extra_args', 'become', 'become_method', 'become_user',
'verbosity', 'check', 'extra_vars', 'playbook_path', 'passwords',
'diff', 'gathering', 'remote_tmp',
])
options = Options(
listtags=False,
listtasks=False,
listhosts=False,
syntax=False,
timeout=60,
connection='local',
module_path='',
forks=10,
remote_user='xiang.gao',
private_key_file='/Users/gaox/.ssh/id_rsa',
ssh_common_args="",
ssh_extra_args="",
sftp_extra_args="",
scp_extra_args="",
become=None,
become_method=None,
become_user=None,
verbosity=None,
extra_vars=[],
check=False,
playbook_path='config/',
passwords=None,
diff=False,
gathering='implicit',
remote_tmp='/tmp/.ansible'
)
# initialize needed objects
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
passwords = dict(vault_pass='secret')
# 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='localhost,')
# 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)
play = PlaybookExecutor(
playbooks=['config/test.yml'],
inventory=inventory,
loader=loader,
options=options,
passwords=passwords,
variable_manager=variable_manager
)
result = play.run()
print(result)
以下是playbook内容:
- hosts: localhost
remote_user: x.g
become: yes
become_method: sudo
gather_facts: no
tasks:
- name: clone topasm web from gitlab.
git:
repo: git@gitlab.com:X.G/web.git
dest: /Users/gx/Desktop/web
clone: yes
update: yes
force: yes
version: master
key_file: /Users/gaox/.ssh/id_rsa
执行结果:
PLAY [localhost] ***************************************************************
TASK [clone topasm web from gitlab.] *******************************************
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "sudo: unknown user: None\nsudo: unable to initialize policy plugin\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
to retry, use: --limit @/Users/gaox/PycharmProjects/CMDB/cicd/config/test.retry
PLAY RECAP *********************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=1
2
不知道为什么会出错
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论