Vitali Plagov
Vitali Plagov

Reputation: 762

Set a friendly name for a package when installing using with_items loop

I have an Ansible task that installs several packages by a direct RPM link:

- name: Install packages by a direct RPM
  become: true
  package: name={{ item }} state=present
  with_items:
    - https://go.skype.com/skypeforlinux-64.rpm
    - https://zoom.us/client/latest/zoom_x86_64.rpm

When I run it, the output is as follows:

TASK [Install packages by a direct RPM] *******************************
ok: [localhost] => (item=https://go.skype.com/skypeforlinux-64.rpm)
ok: [localhost] => (item=https://zoom.us/client/latest/zoom_x86_64.rpm)

Is it possible to change it so that output will print a friendly name of a package, like "Skype", "Zoom", etc. instead of an URL?

Upvotes: 1

Views: 151

Answers (1)

Zeitounator
Zeitounator

Reputation: 44760

Although this is not what you should actually do (see below), this can be achieved by adding control to your loop and modifying your package list a bit.

- name: Install packages by a direct RPM
  become: true
  package:
    name: "{{ item.link }}"
    state: present
  with_items:
    - link: https://go.skype.com/skypeforlinux-64.rpm
      name: Skype
    - link: https://zoom.us/client/latest/zoom_x86_64.rpm
      name: Zoom
  loop_control:
    label: "{{ item.name }}"

Meanwhile, this is still bad practice in this case because you should not loop over agnostic package and alike specific yum, apt... modules. You can pass the list of packages to install directly in the name option. The documentation for this is lacking for package but is clearly explained on the specific modules pages.

This is how to achieve the same result as above with a better performance (one single call to yum/dnf on the system) and less potential errors (cross dependencies between packages in the list...).

- name: Install Skype and Zoom by direct RPM
  become: true
  package:
    name:
      - https://go.skype.com/skypeforlinux-64.rpm
      - https://zoom.us/client/latest/zoom_x86_64.rpm
    state: present

If you still want to be dynamic for the names and link list in case you want to add more packages to the task later, here is an example of a possible way to handle that:

- name: Install from rpm link ({{ packages | map(attribute='name') | join(', ') }})
  vars:
    packages:
      - link: https://go.skype.com/skypeforlinux-64.rpm
        name: Skype
      - link: https://zoom.us/client/latest/zoom_x86_64.rpm
        name: Zoom
  package:
    name: "{{ packages | map(attribute='link') | list }}"
    state: present

Upvotes: 2

Related Questions