当尝试在模板中使用预定义的变量时,我有些困惑。我的目的是我希望我的template.xml文件包含vars yaml文件中已经定义的正确信息。
例如,对于每个namevm,将具有每个模板,这些模板已经包含vars文件中定义的每个信息。但是不幸的是,当我运行我的剧本时,我收到以下错误消息,即变量'vmname'未定义,对此我感到困惑。
你知道我错过了哪一部分吗?
TASK [createvm : modify db template] ********************************************
fatal: [127.0.0.1]: FAILED! => {
"msg": "The task includes an option with an undefined variable. The error was : 'list object' has no attribute 'vmname'. The offending line appears to be:\n\n\n- name: modify db template\n ^ here\n" }
我的剧本的样子:
- name: Prepare DB component
hosts: 127.0.0.1
connection: local
roles:
- { role: "createvm" }
我的角色/createvm/tasks/main.yml如下:
- name: modify db template
template:
src: template.xml
dest: /home/synthesizer/{{ settings.vmname }}.xml
vars:
settings: "{{ dbserver }}"
- name: modify loadbalancer template
template:
src: template.xml
dest: /home/synthesizer/{{ settings.vmname }}.xml
vars:
settings: "{{ loadbalancer }}"
- name: modify forwarder template
template:
src: template.xml
dest: /home/synthesizer/{{ settings.vmname }}.xml
vars:
settings: "{{ forwarder }}"
这是roles / createvm / vars / main.yml,看起来像:
loadbalancer:
- vmname: elbi1
memory: 1024
cpu: 2
- vmname: elbi2
memory: 2048
cpu: 3
forwarder:
- vmname: efwe1
memory: 1024
cpu: 1
- vmname: efwe2
memory: 4096
cpu: 3
dbserver:
- vmname: dibi1
memory: 1024
cpu: 3
- vmname: dibi2
memory: 2048
cpu: 1
最后这就是我的角色/createvm/templates/templates.xml的样子:
<name>{{settings.vmname}}</name>
<memory unit='KiB'>{{settings.memory}}</memory>
<vcpu placement='static'>{{settings.cpu}}</vcpu>
答案 0 :(得分:0)
要遍历vars列表,您必须使用loop
模块,以便可以通过当前使用的点运算符访问列表的各个元素。
您必须将tasks/main.yml
修改为:
---
- name: modify db template
template:
src: template.xml
dest: "/home/synthesizer/ {{ db.vmname }}.xml"
loop: "{{ dbserver }}"
loop_control:
loop_var: db
- name: modify loadbalancer template
template:
src: template.xml
dest: "/home/synthesizer/{{ lb.vmname }}.xml"
loop: "{{ loadbalancer }}"
loop_control:
loop_var: lb
- name: modify forwarder template
template:
src: template.xml
dest: "/home/synthesizer/{{ fw.vmname }}.xml"
loop: "{{ forwarder }}"
loop_control:
loop_var: fw
现在,使用此方法,您可以遍历vars单个列表。希望这会有所帮助!