pratham
pratham

Reputation: 25

ansible loop with items

I can get information for Individual Package Version like this

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

I am trying to use a loop for a list, but I am unable to quote the {{item}}.

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

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

I get the following error message

"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute '{{item}}'

How do I make this work ?

Upvotes: 1

Views: 1362

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39069

You don't need to quote it or put it in curly bracers, you are already in curly bracers:

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

Fully working playbook:

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

Gives this recap:

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: try not to mix YAML and JSON notation, your software array is in JSON, while the rest of your playbook is in YAML.

Upvotes: 1

Related Questions