我正在使用 ansible 2.9,我想知道是否可以使用变量而不是实际的模块名称。 例如:
---
- name: A Network play
hosts: routers
vars:
router_module: ios_command
tasks:
- name: a network task
{{router_module}}:
commands:
- show ip int brief
不。您不能对模块使用变量,但可以从模板动态创建包含任务的文件,并将这些文件包含在 playbook 中。例如,请参阅下面的剧本和模板
shell> cat test.yml
- hosts: localhost
vars:
pb_tasks:
- module: debug
params:
- {key: var, val: inventory_hostname}
- module: debug
params:
- {key: msg, val: End of dynamic play}
tasks:
- file:
state: directory
path: tasks
- template:
src: task.yml.j2
dest: tasks/task-{{ ansible_loop.index }}.yml
loop: "{{ pb_tasks }}"
loop_control:
extended: true
- include_tasks: tasks/task-{{ ansible_loop.index }}.yml
loop: "{{ pb_tasks }}"
loop_control:
extended: true
shell> cat task.yml.j2
- {{ item.module }}:
{% for param in item.params %}
{{ param.key }}: {{ param.val }}
{% endfor %}
在循环中,任务“模板”使用任务创建文件
shell> tree tasks
tasks
├── task-1.yml
└── task-2.yml
0 directories, 2 files
shell> cat tasks/task-1.yml
- debug:
var: inventory_hostname
shell> cat tasks/task-2.yml
- debug:
msg: End of dynamic play
剧本中的下一个任务将这些文件包含在循环中。该剧本给出了
shell> ansible-playbook test.yml
PLAY [localhost] ****
TASK [file] ****
ok: [localhost]
TASK [template] ****
changed: [localhost] => (item={'module': 'debug', 'params': [{'key': 'var', 'val': 'inventory_hostname'}]})
changed: [localhost] => (item={'module': 'debug', 'params': [{'key': 'msg', 'val': 'End of dynamic play'}]})
TASK [include_tasks] ****
included: /scratch/tasks/task-1.yml for localhost
included: /scratch/tasks/task-2.yml for localhost
TASK [debug] ****
ok: [localhost] => {
"inventory_hostname": "localhost"
}
TASK [debug] ****
ok: [localhost] => {
"msg": "End of dynamic play"
}
PLAY RECAP ****
localhost: ok=6 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
同样可以通过动态创建的剧本来简化。例如,请参阅下面的剧本和模板
shell> cat test.yml
- name: Create playbook from template
hosts: localhost
gather_facts: false
vars:
pb_tasks:
- module: debug
params:
- {key: var, val: inventory_hostname}
- module: debug
params:
- {key: msg, val: End of play}
tasks:
- template:
src: playbook.yml.j2
dest: playbook.yml
shell> cat playbook.yml.j2
- hosts: localhost
gather_facts: false
tasks:
{% for item in pb_tasks %}
- {{ item.module }}:
{% for param in item.params %}
{{ param.key }}: {{ param.val }}
{% endfor %}
{% endfor %}
任务“模板”创建剧本
shell> cat playbook.yml
- hosts: localhost
gather_facts: false
tasks:
- debug:
var: inventory_hostname
- debug:
msg: End of play
然后剧本给出了
shell> ansible-playbook playbook.yml
PLAY [localhost] ****
TASK [debug] ****
ok: [localhost] => {
"inventory_hostname": "localhost"
}
TASK [debug] ****
ok: [localhost] => {
"msg": "End of play"
}
PLAY RECAP ****
localhost: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0