【问题标题】:ansible loop with items带有项目的ansible循环
【发布时间】:2020-06-25 19:27:07
【问题描述】:

我可以像这样获取单个包版本的信息

- name: Print zsh Version
  debug:
    msg: "{{ ansible_facts.packages['zsh'][0].version }}"
  when: " 'zsh' in ansible_facts.packages"

我正在尝试使用loop 作为列表,但我无法引用{{item}}

 software: ['ksh','zsh','bash']

- name: Print Softwre Versions
  debug:
    msg: "{{ ansible_facts.packages['{{item}}'][0].version }}"
  with_items: "{{ software }}"

我收到以下错误消息

"msg": "该任务包含一个带有未定义变量的选项。错误是:'dict object' has no attribute '{{item}}'

我该如何进行这项工作?

【问题讨论】:

    标签: loops ansible


    【解决方案1】:

    你不需要引用它或把它放在花括号里,你已经在花括号里了:

    - name: Print software versions
      debug:
        msg: "{{ ansible_facts.packages[item][0].version }}"
      vars:
        software: 
          - 'ksh'
          - 'zsh'
          - 'bash'
      loop: "{{ software }}"
    

    完整的工作手册:

    - hosts: localhost
      gather_facts: no
    
      tasks:
        - name: Gather package facts
          package_facts:
            manager: auto
    
        - name: Print software versions
          debug:
            msg: "{{ ansible_facts.packages[item][0].version }}"
          vars:
            software:
              - 'ksh'
              - 'zsh'
              - 'bash'
          loop: "{{ software }}"
    

    回顾一下:

    PLAY [localhost] ***************************************************************
    
    TASK [Gather package facts] ****************************************************
    ok: [localhost]
    
    TASK [Print software versions] *************************************************
    ok: [localhost] => (item=ksh) => {
        "msg": "2020.0.0-5"
    }
    ok: [localhost] => (item=zsh) => {
        "msg": "5.8-3ubuntu1"
    }
    ok: [localhost] => (item=bash) => {
        "msg": "5.0-6ubuntu1"
    }
    
    PLAY RECAP *********************************************************************
    localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    

    PS:尽量不要混合使用 YAML 和 JSON 表示法,你的 software 数组是 JSON,而你的剧本的其余部分是 YAML。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 2020-11-26
      • 1970-01-01
      相关资源
      最近更新 更多