Ansible loops and conditions with arrays

ansiblestdout

I want to be able to control the behaviour of a module by specifying a changed_when condition. This works fine when executing a simple task like the one in the docs:

- command: some command
  register: command_result
  changed_when: "command_result.rc != 2"

The problem comes when I start using loops. I can't figure out how to access stderr, stdout, rc results from the current iteration of a loop. For example:

- command: aptly mirror update some-mirror
  register: aptly_output
  changed_when: "?item?.stdout | search('Download queue: 0 items')"

All results go to aptly_output.results, but how do I access the result of the current iteration?

Best Answer

In one of our roles we do this:

- name: themes | activate
  command: "wp-cli --allow-root --no-color --path='{{ item.0.path }}' theme activate {{ item.1.name }}"
  register: check_activate_theme
  changed_when: "'Success: Switched to' in check_activate_theme.stdout"
  with_subelements:
    - wordpress_installs
    - themes
  when: item.1.name and item.1.activate | default(false)
  tags:
    - wordpress-themes-activate-theme

I think this should also work for your use case.