使用Ansible2.6 Python Api执行playbook任务

发布于 2022-09-07 19:55:28 字数 4261 浏览 26 评论 0

以下是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文