Perform a task if there is a search result


I’m using the following two tasks to replace the OpenJDK menu entry file on a Linux desktop. The file is a bit of a moving target, and its name sometimes changes from one release to the next.

# OpenJDK Policy Tool menu file is a moving target
- name: Find OpenJDK menu entry location
    paths: /usr/share/applications
    patterns: 'java*openjdk*.desktop'
  register: java_menufile

- name: Don't show OpenJDK Policy Tool in the menu
    dest: "{{ java_menufile.files[0].path }}"
    content: |
      [Desktop Entry]
    owner: root
    group: root
    mode: 0644
  notify: Update desktop database

I’d like to add a little security here which says something like “don’t perform the second task if the search yields no results”.

I tried adding this:

when: java_menufile.stat.exists

But this doesn’t seem to work. I must be doing something wrong.

Any suggestions ?

The parameter in the registered variable *.stats.exists is for ansible.builtin.stat module.
The structure of the registered variables are very different for each modules.

To get the structure of the returned variable, refer to the “Return Values” section in the docs for each modules.

Also dumping the registered variable is helpful to know its structure.

- name: Dump registered variable
    var: java_menufile

Anyway once you know the structure of the return value, you can consider how to make it a when condition. For your cases, perhaps

when: java_menufile.matched

is the way.


Thanks very much ! It works now.

Glad to hear that!
To close this thread, could you please mark my post as a solution, if you don’t have any further questions? Thanks!