从另一个 Ansible 模块调用 Ansible 模块?

de-*_*rob 5 python automation python-2.7 ansible ansible-2.x

是否可以以编程方式从另一个 Ansible 模块调用 Ansible 模块?

语境

我一直在通过 Python (ucsmsdk) 和 Ansible 与 Cisco UCS 合作,以创建一种自动化服务配置文件模板(从现在开始的 SPT)的方法。我创建了符合相应 Git 存储库中设置的标准的api模块

虽然我能够使用 Ansible playbook 创建这些 SPT,但它需要大量重复使用的属性来创建每个单独的项目并遵循它们的长链父/子关系。我想删除所有这些重用并通过提供所有参数来简化项目的创建,我需要一次性完成它们的结构。

下面的例子显示了我想要的当前系统。

当前的

tasks:
- name: create ls server
  ls_server_module:
    name: ex
    other_args:
    creds: 
- name: create VNIC Ether
  vnic_ether_module:
    name: ex_child
    parent: ex
    other_args: 
    creds: 
- name: create VNIC Ether If (VLAN)
  vnic_ether_if_module:
    name: ex_child_child
    parent: ex_child
    creds: 
- name: create VNIC Ether
  vnic_ether_module:
    name: ex_child_2
    parent: ex
    other_args: 
    creds: 
Run Code Online (Sandbox Code Playgroud)

想要的

tasks:
- name: create template
  spt_module:
    name: ex
    other_args:
    creds: 
    LAN:
      VNIC:
      - name: ex_child
        other_args:
        vlans:
        - ex_child_child
      - name: ex_child_2
        other_args:
Run Code Online (Sandbox Code Playgroud)

目前,我唯一的障碍是通过调用这些以动态和编程方式创建对象的模块来诱导一些代码重用。

Kon*_*rov 6

您不能从其他模块中执行模块,因为 Ansible 中的模块是自包含实体,它们被打包在控制器上并交付给远程主机执行。

但是有针对这种情况的动作插件。您可以创建动作插件spt_module(它将在 Ansible 控制器上本地执行),该插件可以根据lan/vnic参数依次执行多个不同的模块。

这就是你的 action ( spt_module.py) 插件的样子(非常简化):

from ansible.plugins.action import ActionBase

class ActionModule(ActionBase):

    def run(self, tmp=None, task_vars=None):

        result = super(ActionModule, self).run(tmp, task_vars)

        vnic_list = self._task.args['LAN']['VNIC']
        common_args = {}
        common_args['name'] = self._task.args['name']

        res = {}
        res['create_server'] = self._execute_module(module_name='ls_server_module', module_args=common_args, task_vars=task_vars, tmp=tmp)
        for vnic in vnic_list:
          module_args = common_args.copy()
          module_args['other_args'] = vnic['other_args']
          res['vnic_'+vnic['name']] = self._execute_module(module_name='vnic_ether_module', module_args=module_args, task_vars=task_vars, tmp=tmp)
        return res
Run Code Online (Sandbox Code Playgroud)

代码未经测试(可能有错误、错别字)。