You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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) }}"

解决方案

错误原因

  1. 模板语法嵌套错误:在{{ }}内部又嵌套了{{ }},Jinja2模板不允许这种写法
  2. 无需使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:34:54