Ansible 模板循环

Ansible template loop

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

{% 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__'"
}

我是 ansible 模板的新手。我通过谷歌搜索写了这个。请善待...

您可能希望将逻辑放入字典而不是 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 %}