在Ansible中,可以使用变量替换和任务委派的组合来实现动态的任务执行。以下是一个示例解决方法:
example.yml
的Ansible Playbook文件。---
- name: Example Playbook
hosts: all
become: true
vars:
delegate_host: "{{ inventory_hostname }}"
task_template: "{{ inventory_hostname }}"
tasks:
- name: Delegate task
delegate_to: "{{ delegate_host }}"
shell: echo "This task is delegated to {{ delegate_host }}."
- name: Replace variable in task template
template:
src: task_template.yml
dest: /tmp/task_{{ inventory_hostname }}.yml
- name: Include task template
include_tasks: "/tmp/task_{{ inventory_hostname }}.yml"
解释:
delegate_host
变量用于指定要委派任务的主机。task_template
变量用于指定任务模板文件的名称。task_template.yml
的任务模板文件。---
- name: "{{ task_template }}"
shell: echo "This is task template for {{ task_template }}."
解释:
{{ task_template }}
是用于替换任务名称的变量。ansible-playbook example.yml
结果:
delegate_host
主机,并输出一条相关信息。template
模块将任务模板文件复制到目标主机,并将文件名中的变量替换为当前主机名。include_tasks
模块包含被替换后的任务模板文件。这样,就实现了使用变量替换和任务委派的组合来动态执行任务的解决方法。