Ansible循环中用lookup结合变量获取字典内容报错求助
Ansible根据发行版获取字典数据并循环的问题解决
问题场景
需要基于ansible_distribution变量从预定义字典中获取对应发行版的repo列表,在with_items循环中使用来配置yum源,但原代码的lookup写法错误导致模板解析失败。
原Playbook代码:
- hosts: all gather_facts: true become: yes vars: distributions: Centos: repos: - repo_name: 'repo1' baseurl: 'url1' file: 'file1' gpgkey: 'gpgkey1' Rocky: repos: - repo_name: 'repo2' baseurl: 'url2' file: 'file2' gpgkey: 'gpgkey2' tasks: - name: Add Yum Repo become: yes yum_repository: name: "{{ item.repo_name }}" description: EpelUpdate baseurl: "{{ item.baseurl }}" file: " {{ item.file }}" gpgcheck: 0 gpgkey: "{{ item.gpgkey }}" with_items: - "{{ lookup(vars, distributions.{{ ansible_distribution }}.repos) }}" #<-- 该行错误
执行后报错:
"msg": "template error while templating string: expected name or number. String: {{ lookup(vars, distributions.{{ ansible_distribution }}.repos) }}"
解决方案
错误原因
- 模板语法嵌套错误:在
{{ }}内部又嵌套了{{ }},Jinja2模板不允许这种写法 - 无需使用
lookup(vars):distributions是已定义的变量,直接通过字典索引即可获取对应发行版的repo数据,不需要通过lookup检索变量。
修正后的代码
把with_items的内容改成直接引用变量索引的形式:
- hosts: all gather_facts: true become: yes vars: distributions: Centos: repos: - repo_name: 'repo1' baseurl: 'url1' file: 'file1' gpgkey: 'gpgkey1' Rocky: repos: - repo_name: 'repo2' baseurl: 'url2' file: 'file2' gpgkey: 'gpgkey2' tasks: - name: Add Yum Repo become: yes yum_repository: name: "{{ item.repo_name }}" description: EpelUpdate baseurl: "{{ item.baseurl }}" file: "{{ item.file }}" gpgcheck: 0 gpgkey: "{{ item.gpgkey }}" with_items: "{{ distributions[ansible_distribution].repos }}"
补充说明
- 使用
distributions[ansible_distribution]是Jinja2中通过变量作为字典键取值的标准写法,比distributions.{{ ansible_distribution }}更稳妥,尤其当键名包含特殊字符时 - 同时修正了
file字段的多余空格,避免生成的repo文件路径出现空格问题
内容的提问来源于stack exchange,提问作者Kucharsky
相关产品推荐
相关产品推荐

