moocan
moocan

Reputation: 141

Ansible: variable in variable / loop or iterating through item

Here is a simple vars file we have to debug ./roles/test/vars/{{ ansible_distribution|lower }}/apt-packages.yml

  packages:
    required:
      - htop
#      - aptitude

  package:
    htop:
      allow_unauthenticated: no
      autoclean: no
      autoremove: no
      cache_valid_time: 0
#    default_release:
      force: no
      force_apt_get: no
      install_recommends: yes
      only_upgrade: no
      purge: no 
      state: latest
      update_cache: yes
      upgrade: no

Here is a simple task to debug ./roles/test/tasks/main.yml

- name: "Register variable"
  include_vars:
    #dir: vars/ubuntu
    file: "vars/{{ ansible_distribution|lower }}/apt-packages.yml"
    name: apt_install

- name: "This a test"
  apt:
    name: "{{item}}"
    cache_valid_time: "{{ apt_install.package[item].cache_valid_time }}"
    state: "{{ apt_install.package[item].state }}"
    update_cache: "{{ apt_install.package[item].update_cache }}"
  with_items: "{{ apt_install.packages.required }}"

./roles/test-playbook.yml

- name: "playbook test"
  hosts: localhost
  roles:
    - role: test
  become: true
  become_user: root
  become_method: sudo

using following answer stackoverflow.com/questions/29276198 we are trying to loop through items and get item related values.

Tasks is looping well through items but it is impossible to retrieve related variable with [item] syntax or any other one we have tested.

We have always the same error

fatal: [localhost]: FAILED! => { "msg": "The task includes an option with an undefined variable. The error was: dict object has no element [u'htop']

But calling directly the variable works

- name: "echo variable test"
  debug: 
    msg: "{{ apt_install.package.htop.allow_unauthenticated }}"

What is the right syntax to get current loop value of a variable and use it inside another variable to retrieve related value ... (inside the same task) ?

So far it's we who are going around in circles without end !

Kind Regards

Upvotes: 1

Views: 4058

Answers (1)

moocan
moocan

Reputation: 141

This is fully working using a loop / loop_control instead of with_items

- name: "This a test"
  apt:
    name: "{{item}}"
    cache_valid_time: "{{ apt_install.package[item].cache_valid_time }}"
    state: "{{ apt_install.package[item].state }}"
    update_cache: "{{ apt_install.package[item].update_cache }}"
  loop: "{{ apt_install.packages.required|flatten(levels=1) }}"
  loop_control:
    index_var: index

So as it we can define different settings for each package and for each distrib. Now I can export too settings for each package in different var files.

Learning is hard :)

Upvotes: 1

Related Questions