可靠的模板循环



我正在尝试循环一个字典并设置一个变量。这是我的模板文件中的内容。

{% for item in db_server() %}
{% if item.name in fqdn.stdout and item.mysql == "mysql-5-5-28" %}
{% set version = "mysql-5.5.28-linux2.6-x86_64" %}
{% elif item.name in fqdn.stdout and item.mysql == "mysql-5-1-51" %}
{% set version = "mysql-5.1.51-linux-x86_64-glibc23" %}
{% endif %}
{% endfor %}

我的var文件是

db_server:
- name: "test1"
mysql: "mysql_5_5_28"
- name: "test2"
mysql: "mysql_5_5_28"
- name: "test3"
mysql: "mysql_5_5_28"

我收到一个错误

fatal: [st-cms-db2]: FAILED! => {
"changed": false, 
"msg": "AttributeError: 'list' object has no attribute '__call__'"
}

我是易翻译模板的新手。我是通过谷歌搜索写的。请善良。。。

您可能希望将逻辑放入字典中,而不是Jinja模板中。例如,创建字典

versions:
mysql_5_5_28: mysql-5.5.28-linux2.6-x86_64
mysql_5_1_51: mysql-5.1.51-linux-x86_64-glibc23

然后下面的剧本实现了逻辑

shell> cat pb.yml
- hosts: localhost
vars:
versions:
mysql_5_5_28: mysql-5.5.28-linux2.6-x86_64
mysql_5_1_51: mysql-5.1.51-linux-x86_64-glibc23
db_server:
- name: "test1"
mysql: "mysql_5_5_28"
- name: "test2"
mysql: "mysql_5_5_28"
- name: "test3"
mysql: "mysql_5_1_51"
tasks:
- debug:
msg: "{{ item.name }} {{ versions[item.mysql] }}"
loop: "{{ db_server }}"
# when: item.name in fqdn.stdout

给出

shell> ansible-playbook pb.yml | grep msg
msg: test1 mysql-5.5.28-linux2.6-x86_64
msg: test2 mysql-5.5.28-linux2.6-x86_64
msg: test3 mysql-5.1.51-linux-x86_64-glibc23

根据您的需求调整库存和其他条件(例如fqdn.stdout(。将名称和版本放入字典将进一步简化代码。例如,

db_server:
test1:
mysql: "mysql_5_5_28"
test2:
mysql: "mysql_5_5_28"
test3:
mysql: "mysql_5_1_51"

然后下面的剧本实现了多个主机的逻辑

shell> cat pb.yml
- hosts: test1,test2,test3
gather_facts: false
vars:
versions:
mysql_5_5_28: mysql-5.5.28-linux2.6-x86_64
mysql_5_1_51: mysql-5.1.51-linux-x86_64-glibc23
db_server:
test1:
mysql: "mysql_5_5_28"
test2:
mysql: "mysql_5_5_28"
test3:
mysql: "mysql_5_1_51"
tasks:
- set_fact:
version: "{{ versions[db_server[inventory_hostname].mysql] }}"
- debug:
msg: "{{ inventory_hostname }} {{ version }}"

给出相同的结果

shell> ansible-playbook pb.yml | grep msg
msg: test2 mysql-5.5.28-linux2.6-x86_64
msg: test1 mysql-5.5.28-linux2.6-x86_64
msg: test3 mysql-5.1.51-linux-x86_64-glibc23

如果您仍然想继续使用模板,请尝试任务和下面的模板

- set_fact:
version: "{{ lookup('template', 'template.j2') }}"
shell> cat template.j2
{% for item in db_server %}
{% if item.name in fqdn.stdout and item.mysql == "mysql_5_5_28" %}
"mysql-5.5.28-linux2.6-x86_64"
{% elif item.name in fqdn.stdout and item.mysql == "mysql_5_1_51" %}
"mysql-5.1.51-linux-x86_64-glibc23"
{% endif %}
{% endfor %}

相关内容

  • 没有找到相关文章

最新更新