是否可以从Ansible模块内运行任务列表?



我正在开发一个包含许多复杂系统配置剧本的集合。然而,我想将它们的使用简化为一个模块插件,名为"install"。在模块的Python代码中,将决定调用哪个剧本来执行实际任务。说

- name: Some playbook written by the end user
hosts: all
tasks:
...
- install:
name: docker
version: latest
state: present
...

基于指定的name,的Python代码会安装吗?模块以编程方式调用适当的剧本来执行最新版本的Docker的安装。这些剧本也包括在集合中。

如果任务列表比剧本更适合,那么它就是任务列表。

事实上,我并不介意精确的实现。只要:

  1. 所有东西都被打包成一个集合
  2. 最终用户通过一个'install'任务完成所有操作,如上所示

这可能吗?

是。这是有可能的。例如,给定文件

中的变量
shell> cat foo_bar_install.yml
foo_bar_install:
name: docker
version: latest
state: present

创建集合中的剧本foo.bar

shell> tree collections/ansible_collections/foo/bar/
collections/ansible_collections/foo/bar/
├── galaxy.yml
└── playbooks
├── install_docker.yml
└── install.yml
1 directory, 3 files
shell> cat collections/ansible_collections/foo/bar/playbooks/install_docker.yml
- name: Install docker
hosts: all
gather_facts: false
tasks:
- debug:
msg: |
Playbook foo.bar.install_docker.yml
version: {{ version|d('UNDEF') }}
state: {{ state|d('UNDEF') }}
shell> cat collections/ansible_collections/foo/bar/playbooks/install.yml 
- import_playbook: "foo.bar.install_{{ foo_bar_install.name }}.yml"
vars:
version: "{{ foo_bar_install.version }}"
state: "{{ foo_bar_install.state }}"

给定库存

shell> cat hosts 
host1
host2

运行playbookfoo.bar.install。并在文件foo_bar_install.yml

中提供额外的变量
shell> ansible-playbook foo.bar.install.yml -e @foo_bar_install.yml
PLAY [Install docker] ************************************************************************
TASK [debug] *********************************************************************************
ok: [host1] => 
msg: |-
Playbook foo.bar.install_docker.yml
version: latest
state: present
ok: [host2] => 
msg: |-
Playbook foo.bar.install_docker.yml
version: latest
state: present
PLAY RECAP ***********************************************************************************
host1: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host2: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

最新更新