python 调用 ansible api

python 调用 ansible api


1.安装

   pip install ansible

注意:ansible 只能Linux运行
可以尝试pycharm 远程调试

2.调用方式

1.adhoc 直接调用ansible模块


# 指定 ansible 安装的modules
MODULE_PATH = "//home//production//env//devops//lib//python3.7//site-packages//ansible//modules"

def adhoc(host_list, task_list, remote_user='root', become=None, become_user=None):
    # since the API is constructed for CLI it expects certain options to always be set in the context object
    context.CLIARGS = ImmutableDict(connection='smart', remote_user=remote_user, verbosity=3, module_path=MODULE_PATH,
                                    forks=20, become=become,
                                    become_method=None, become_user=become_user, check=False, diff=False)
    # required for
    # https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L204
    sources = ','.join(host_list)
    if len(host_list) == 1:
        sources += ','

    # initialize needed objects
    loader = DataLoader()  # Takes care of finding and reading yaml, json and ini files
    passwords = dict()

    # Instantiate our ResultsCollectorJSONCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
    results_callback = ResultsCollectorJSONCallback()

    # create inventory, use path to host config file as source or hosts in a comma separated string
    inventory = InventoryManager(loader=loader, sources=sources)

    # variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
    variable_manager = VariableManager(loader=loader, inventory=inventory)

    # instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
    # IMPORTANT: This also adds library dirs paths to the module loader
    # IMPORTANT: and so it must be initialized before calling `Play.load()`.
    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
    )

    # create data structure that represents our play, including tasks, this is basically what our YAML loader does internally.
    play_source = dict(
        name="Ansible Play",
        hosts=host_list,
        gather_facts='no',
        tasks=task_list
    )

    # Create play object, playbook objects use .load instead of init or new methods,
    # this will also automatically create the task objects from the info provided in play_source
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # Actually run it
    try:
        result = tqm.run(play)  # most interesting data for a play is actually sent to the callback's methods
    except Exception as e:
        return e
    finally:
        # we always need to cleanup child procs and the structures we use to communicate with them
        tqm.cleanup()
        if loader:
            loader.cleanup_all_tmp_files()

    # Remove ansible tmpdir
    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    def get_result():
        results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
        for _hosts, result in results_callback.host_ok.items():
            results_raw['success'][_hosts] = result._result
        for _hosts, result in results_callback.host_failed.items():
            results_raw['failed'][_hosts] = result._result
        for _hosts, result in results_callback.host_unreachable.items():
            results_raw['unreachable'][_hosts] = result._result

        return results_raw

    _get_result = get_result()
    return _get_result

2.playbook 调用yaml脚本

def execPlaybook(playbooks,host_list, remote_user='production', become=None, become_user=None):
    context.CLIARGS = ImmutableDict(connection='smart', remote_user=remote_user, verbosity=3, module_path=MODULE_PATH,
                                    forks=20, become=become, syntax=None, start_at_task=None,
                                    become_method=None, become_user=become_user, check=False, diff=False)

    sources = ','.join(host_list)
    if len(host_list) == 1:
        sources += ','

    # initialize needed objects
    loader = DataLoader()  # Takes care of finding and reading yaml, json and ini files
    passwords = dict()

    # Instantiate our ResultsCollectorJSONCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
    results_callback = ResultsCollectorJSONCallback()

    # create inventory, use path to host config file as source or hosts in a comma separated string
    inventory = InventoryManager(loader=loader, sources=sources)

    # variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
    variable_manager = VariableManager(loader=loader, inventory=inventory)


    playbook = PlaybookExecutor(playbooks=playbooks,
                                inventory=inventory,
                                variable_manager=variable_manager,
                                loader=loader,
                                passwords=passwords)

    # 使用回调函数
    playbook._tqm._stdout_callback = results_callback
    try:
        result = playbook.run()
    except Exception as e:
        return e

    # Remove ansible tmpdir
    #shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    def get_result():
        results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
        for _hosts, result in results_callback.host_ok.items():
            results_raw['success'][_hosts] = result._result
        for _hosts, result in results_callback.host_failed.items():
            results_raw['failed'][_hosts] = result._result
        for _hosts, result in results_callback.host_unreachable.items():
            results_raw['unreachable'][_hosts] = result._result

        return results_raw

    _get_result = get_result()
    return _get_result

3.设置回调方法

class ResultsCollectorJSONCallback(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 __init__(self, *args, **kwargs):
        super(ResultsCollectorJSONCallback, self).__init__(*args, **kwargs)
        self.host_ok = {}
        self.host_unreachable = {}
        self.host_failed = {}

    def v2_runner_on_unreachable(self, result):
        host = result._host
        self.host_unreachable[result._host.get_name()] = {
            "unreachable": result._result.get("unreachable"),
            "msg": result._result.get("msg")}

    def v2_runner_on_ok(self, result, *args, **kwargs):
        """Print a json representation of the result.

        Also, store the result in an instance attribute for retrieval later
        """
        self.host_ok[result._host.get_name()] = {
            "stdout_lines": result._result.get("stdout_lines"),
            "stderr_lines": result._result.get("stderr_lines"),
            "cmd": result._result.get("cmd"),
            "delta": result._result.get("delta"),
            "start": result._result.get("start"),
            'end': result._result.get("end"),
            "rc": result._result.get("rc"),
            "changed": result._result.get("changed")}

    def v2_runner_on_failed(self, result, *args, **kwargs):
        self.host_failed[result._host.get_name()] = {
            "stdout_lines": result._result.get("stdout_lines"),
            "stderr_lines": result._result.get("stderr_lines"),
            "cmd": result._result.get("cmd"),
            "delta": result._result.get("delta"),
            "start": result._result.get("start"),
            "msg": result._result.get("msg"),
            'end': result._result.get("end"),
            "rc": result._result.get("rc"),
            "changed": result._result.get("changed")
        }

4.main方法使用

if __name__ == '__main__':
    # 指定主机,需要配置ssh
    host=['10.0.0.0','10.0.0.0']
    tasks=[
        # dict(name='222222',action=dict(module="setup")),
        dict(name='222222',action=dict(module="setup",args=dict(filter='ansible_nodename'))),
    result = adhoc(host_list=host,task_list=tasks)
    # result = execPlaybook(playbooks=['test1.yml'],host_list=host)
    print(json.dumps(result, indent=4))
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Ansible调用OpenStack API下载镜像,需要使用以下步骤: 1. 安装python-openstackclient和python-novaclient: ``` $ sudo pip install python-openstackclient python-novaclient ``` 2. 创建一个名为“download_image.yaml”的YAML文件,并在其中定义以下Playbook: ```yaml - hosts: localhost gather_facts: no tasks: - name: Download image os_compute_api: auth: auth_url: "{{ auth_url }}" username: "{{ username }}" password: "{{ password }}" project_name: "{{ project_name }}" project_domain_name: "{{ project_domain_name }}" user_domain_name: "{{ user_domain_name }}" api_version: 2 endpoint_type: public service_name: compute resource: servers server: "{{ server_name }}" action: image.create image_name: "{{ image_name }}" disk_format: "{{ disk_format }}" container_format: "{{ container_format }}" ``` 3. 在上面的Playbook中,将以下变量替换为OpenStack API的凭据和要下载的镜像的详细信息: ``` auth_url: OpenStack API的认证URL username: OpenStack API的用户名 password: OpenStack API的密码 project_name: OpenStack API的项目名称 project_domain_name: OpenStack API的项目域名 user_domain_name: OpenStack API的用户域名 server_name: 要下载镜像的实例名称 image_name: 要下载的镜像名称 disk_format: 镜像的磁盘格式(例如qcow2) container_format: 镜像的容器格式(例如bare) ``` 4. 运行以下命令以使用上述Playbook: ``` $ ansible-playbook download_image.yaml ``` 这将调用OpenStack API并下载指定的镜像。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值