zerocool
zerocool

Reputation: 833

ansible - can't access item in nested list

I'm trying to update /etc/apt/sources.list and /etc/apt/sources.list.d/ in my chrooted location inside one server. There are 3 chroot directories under /opt/chroot.

First, I check if that directory exists, then getting all chroot names, checking version of Debian (updating for wheezy, so major version == 7), finally - finding all relevant files.

Next step would be to iterate through them, but for some reason I can't access all items in registered variables. For example for nginx host i have 3 files, for mysql - 2 files, ftp - 1 file.

This is my playbook where last step is failing because: VARIABLE IS NOT DEFINED

- name: ROOT check if /opt/chroot exists
  tags:
    - fix_wheezy
    - chrootonly
  stat:
    path: /opt/chroot
  register: chrootpath

- name: ROOT get chroot names
  tags:
    - fix_wheezy
    - chrootonly
  shell: 'ls /opt/chroot | grep -v disable'
  register: chroots
  when: chrootpath.stat.exists == True

- name: ROOT get chroot versions
  tags:
    - fix_wheezy
    - chrootonly
  shell: 'chroot /opt/chroot/{{ item }} cut -d. -f1 /etc/debian_version'
  register: chroot_versions
  with_items: "{{ chroots.stdout_lines | default(omit) }}"

- name: CHROOT find list files for upgrade
  tags:
    - fix_wheezy
    - chrootonly
  find:
    paths: '/opt/chroot/{{ item.item }}/etc/apt'
    recurse: yes
    patterns: '*.list'
  register: find_chroot_list
    # var: item.stdout
  with_items: '{{ chroot_versions.results }}'
  when: chroots is defined and chrootpath.stat.exists == True and chroots.stdout.strip() != '' and item.stdout == '7'

- name: CHROOT check what was registered
  tags:
    - fix_wheezy
    - chrootonly
  debug:
    var: item.files.path
  with_items: 
    - '{{ find_chroot_list.results }}'

I am attaching full log of final task: CHROOT check what was registered.

I have actually two questions:

Upvotes: 1

Views: 448

Answers (1)

Zeitounator
Zeitounator

Reputation: 44615

why paths is not available?

In your output, files in each item is a list of maps. Hence, item.files.path does not exists, but item.files[0].path does.

is it possible to iterate through such nested list produced by last task?

Definitely yes and there are several options (subelements, attribute extraction...). In your specific case, I would go for json_query. The following example will return what you are looking for

- name: CHROOT check what was registered
  debug:
    var: item.path
  loop: "{{ find_chroot_list.results | json_query('[].files[]') }}"

Note that json_query requires pip install jmespath

Upvotes: 1

Related Questions