Problem translating part of a Bash script into Ansible

Hi,

Up until recently I’ve been using a bone-headed setup.sh shell script to setup my desktop clients based on Rocky Linux 8 and a heavily customized KDE desktop.

I’ve been learning to use Ansible for some time now (with a few false starts) and I’m currently translating this script into Ansible’s way of doing things:

https://gitlab.com/kikinovak/rocky-8-ansible

In the original setup.sh script I have a replace_menus() function that loops through *.desktop files in /usr/share/applications and other places and replaces some of these with a custom version, but only if they exist in the first place.

I wonder how I could possibly translate this into Ansible code. Here’s what should happen:

  1. loop through all custom desktop entries in the templates/ directory.

  2. If the corresponding .desktop file exists in /usr/share/applications, then replace it with the custom version from templates/.

  3. If it doesn’t exist, then don’t install the template.

In other words: install the template only if the target already exists.

Any idea how I could do that ?

Could one get a list of files that do exist in /usr/share/applications with ansible.builtin.find module – Return a list of files based on specific criteria — Ansible Documentation

Then copy those desktop entries. Perhaps with something similar to:

  - name: Check if we have ssh keys for active users
    check_mode: yes
    local_action: stat path="public_keys/{{ item.name }}.pub"
    register: sshkeys_new
    loop: "{{ local_users }}"
    loop_control:
      label: "{{ item.name }}"
    when:
    - item.active | default(true) | bool

  - name: Add ssh key for user
    authorized_key:
      user:    "{{ item.item.name }}"
      state:   present
      key:     "{{ lookup('file', 'public_keys/{{ item.item.name }}.pub') }}"
    with_items: "{{ sshkeys_new.results }}"
    loop_control:
      label: "{{ item.item.name }}"
    when:
    - item.stat is defined
    - item.stat.exists

The above uses list of names from local_users to check which have an entry in “templates” and then “copies” template to corresponding destination.

1 Like

One could ask what adds the *.desktop to places in the first place? Logically, that play should(?) know what it adds and do also the replace step.