TransWikia.com

Ansible loops and conditions with arrays

Server Fault Asked by EvilTorbalan on January 14, 2021

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?

One 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.

Answered by tersmitten on January 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP